'''
The MIT License (MIT)
Copyright © 2023-2024 pmx1119
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import logging
logging.basicConfig(level=logging.DEBUG, filename='wqt.log', filemode='a', format='[%(asctime)s %(name)s %(levelname)s]: %(message)s', datefmt='%Y/%m/%d/%H:%M:%S')
logging.debug('Starting WinQuickTools.')
from tkinter import filedialog, messagebox, scrolledtext, simpledialog, font, ttk, Toplevel, Listbox, Scrollbar, END, Text
logging.debug('Successfully imported the [MessageBox] function in [Tkinter] and the [SimpleDialog] function')
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
logging.debug('Successfully imported the [Tqdm] function in [Tqdm] module.')
from PIL import Image
logging.debug('Successfully imported the [Tqdm] function in [Tqdm] module.')
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from tkinter.font import Font
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.ticker import MaxNLocator
import numpy as np
import tkinter as tk
import ascii_art
logging.debug('Successfully imported the [ascii_art] module.')
import time
logging.debug('Successfully imported the [time] module.')
import os
logging.debug('Successfully imported the [os] module.')
import webbrowser
logging.debug('Successfully imported the [webbrowser] module.')
import string
logging.debug('Successfully imported the [string] module.')
import subprocess
logging.debug('Successfully imported the [subprocess] module.')
import sys
logging.debug('Successfully imported the [sys] module.')
import random
logging.debug('Successfully imported the [random] module.')
import zipfile
logging.debug('Successfully imported the [zipfile] module.')
import tempfile
logging.debug('Successfully imported the [tempfile] module.')
import math
logging.debug('Successfully imported the [math] module.')
import getpass
logging.debug('Successfully imported the [getpass] module.')
import platform
logging.debug('Successfully imported the [platform] module.')
import requests 
logging.debug('Successfully imported the [requests] module.')
import speedtest
logging.debug('Successfully imported the [speedtest] module.')
import wmi
logging.debug('Successfully imported the [wmi] module.')
import psutil
logging.debug('Successfully imported the [psutil] module.')
import sympy as sp
logging.debug('Successfully imported the [sympy] module.')
import shutil
logging.debug('Successfully imported the [shutil] module.')
import whois
logging.debug('Successfully imported the [whois] module.')
import socket
logging.debug('Successfully imported the [socket] module.')
import threading
logging.debug('Successfully imported the [threading] module.')
import winreg
logging.debug('Successfully imported the [winreg] module.')
import win32api
logging.debug('Successfully imported the [win32api] module.')
import win32file
logging.debug('Successfully imported the [win32file] module.')
import win32con
logging.debug('Successfully imported the [win32con] module.')
import base64
logging.debug('Successfully imported the [base64] module.')
import hashlib
logging.debug('Successfully imported the [hashlib] module.')
import pyvhd
logging.debug('Successfully imported the [pyvhd] module.')
import openai
logging.debug('Successfully imported the [openai] module.')
import ast
logging.debug('Successfully imported the [ast] module.')
import datetime
import keyboard


tttt = 'https://v1.hitokoto.cn/'
ttt = 'https://v1.jinrishici.com/all.json'
rfd = os.path.dirname(os.path.abspath(__file__))
prefix = ''
suffix = '完成'
length = 50
total_iterations = random.randint(80, 100)
RESET_COLORS = b'\033[0m'
PASSWORD1 = ""
TARGET_PROGRAM = ""
IS_RUNNING = False
CMD_ALLOWED = True
PASSWORD_VERIFIED = False
download_stop_event = threading.Event()
download_history_file = "download_history.txt"
beta_user = {
    'Administrator':['', ''],
    'name_B6M4SVQ!m5':['password_i8Qa1g#EWe', 'key_hC5cG-BVgFG-DiEfk-1ueoS-eKyXE'],
    'name_agzfXwj3^a':['password_4h2Q1g#EWe', 'key_pxPy4-utmcp-rzeOz-FRrA2-BwPn4'],
    'name_agzfXwj3^a':['password_4h2Q1g#EWe', 'key_8GYIj-0SUdj-0727D-NFsUl-Tg1jD'],
    'name_wz$0jZPLp8':['password_tL5#wA9&mK', 'key_mWP5I-x31Jd-BYL0l-ZDxCA-RmHAi'],
    'name_Hs$3e1WZrY':['password_gT7)eP2[bV', 'key_H0jHE-NRFSB-eLEuf-Gn30r-vPEMv'],
    'name_WsmWBMaeab':['password_pG4:oF9<qC', 'key_mWP5I-x31Jd-BYL0l-ZDxCA-RmHAi'],
    'name_sTr,bzZ@)7':['password_iH6$iP6_wV', 'key_XpA2G-kaCix-1FWcz-1Bq2K-CZpa2'],
    'name_f~ize3^=BA':['password_uB2:mE2}gC', 'key_Yfoig-7vQya-QW8Mw-BYZuG-uBeY4'],
    'name_WoEU!6e9zZ':['password_qM1)lF3@uG', 'key_1N6X5-rnyX1-A0X78-q1Xpx-LtY7i'],
    'name_AErU!4)Qb^':['password_eG9{vV3$oC', 'key_mCuLm-xWvLS-TIjZm-8LDIz-N3UjK'],
    'name_@)V_Ef*B(1':['password_zF1/gC7]iS', 'key_RODUI-keSeS-KFf4y-QRKRd-cXlUt'],
    'name_i*SS8S!4H*':['password_gX5>sK3_yV', 'key_Yfoig-7vQya-QW8Mw-BYZuG-uBeY4'],
    'name_gfLw0KylAM':['password_mO5~aD4*sF', 'key_aD7LK-WMvc0-qin4u-supM9-yYPtn'],
    'name_21hOHiZ1QR':['password_mN1_hM8*aX', 'key_dLfOw-eoTRN-KVy3m-m0FWK-SQdQk'],
    'name_8AFgTomzJp':['password_eC5~bF3/cU', 'key_bM2a4-HfTCU-RbEz1-7bkSn-k5IFs'],
    'name_g4VzfTguLj':['password_zB1$zT3-uJ', 'key_T7Itr-mefg3-rGpdG-6y1MS-AH8XP'],
    'name_rFk0AtxB2U':['password_tJ7)zF2:fJ', 'key_xH4YS-MFlh2-ezZOI-yYtrY-Fi2Oi'],
    'name_Ir1Sr0xoH0':['password_uO6_fQ9(oV', 'key_wOhM4-5Q387-20AcF-k3i2S-0Lnz6'],
    'name_vlcul6DxfU':['password_cC3`aR8#qN', 'key_BcCKv-7CfyD-OROwH-N5hpi-Vmrid'],
    'name_C0uJ0plnp4':['password_pC1=nX4_fJ', 'key_7QJWu-fVulb-x0062-AKckR-XYRAy'],
    'name_ZVp6BqCKe5':['password_zP8*tV4&cM', 'key_JvK5t-NfbGi-4ughq-S3tBY-c89l5'],
    'name_NnTEyx9lyr':['password_oS0$mL8[rV', 'key_ESaXZ-QT1Pc-cpjF2-qIsii-Ofanb'],
    'name_6M9Hyg#$fs':['password_bN9[uK0>xJ', 'key_1rOJs-o6PIU-7fYKw-GLtXU-Zy47V'],
}
software_list = {
    "微信": "https://dldir1v6.qq.com/weixin/Windows/WeChatSetup.exe",
    "QQ": "https://dldir1.qq.com/qqfile/qq/QQNT/Windows/QQ_9.9.15_241009_x64_01.exe",
    "Python": "https://www.python.org/ftp/python/3.13.2/python-3.13.2-amd64.exe",
    "火绒安全软件": "https://down-tencent.huorong.cn/sysdiag-all-x64-6.0.5.3-2025.02.24.1.exe",
    "360安全卫士": "",
    "ToDesk": "https://dl.todesk.com/irrigation/ToDesk_4.7.6.3.exe",
    "傲梅分区助手": "https://www.disktool.cn/go/download/PAInstall.zip",
    "DiskGenius": "https://c1029.dmpdmp.com/857646ae6c29902c45ff76287862d7bf/67bc8ef2/2024/08/15/ab04cbc49dbe0e40262bc39a4881f04a.zip?fn=DG5611580_x64.zip",
    "PowerToys": "https://github.com/microsoft/PowerToys/releases/download/v0.88.0/PowerToysUserSetup-0.88.0-x64.exe",
    "WPS Office": "https://official-package.wpscdn.cn/wps/download/WPS_Setup_20305.exe",
    "7-Zip": "https://www.7-zip.org/a/7z2409-x64.exe",
    "Steam": "https://media.cdn.queniuqe.com/client/installer/SteamSetup.exe",
    "VMware Workstation Pro": "",
    "哔哩哔哩bilibili": "https://dl.hdslb.com/mobile/fixed/bili_win/bili_win-install.exe",
    "抖音": "https://www.douyin.com/download/pc/obj/douyin-pc-web/douyin-pc-client/7044145585217083655/releases/12289031/5.5.0/win32-ia32/douyin-downloader-v5.5.0-win32-ia32-douyincold.exe",
    "Visual Studio Code": "https://code.visualstudio.com/sha/download?build=stable&os=win32-x64-user",
    "PowerShell": r"https://objects.githubusercontent.com/github-production-release-asset-2e65be/49609581/6c51b2ed-2a54-4ea4-9efd-98d7fc3427be?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=releaseassetproduction%2F20250224%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250224T150120Z&X-Amz-Expires=300&X-Amz-Signature=0971eadf839e4130e8752625af892c9591c1a56cff650daf10ae729fea9da8e8&X-Amz-SignedHeaders=host&response-content-disposition=attachment%3B%20filename%3DPowerShell-7.5.0-win-x64.msi&response-content-type=application%2Foctet-stream",
    "Ollama": "https://ollama.com/download/OllamaSetup.exe",
    "剪映": r"https://www.capcut.cn/download-guidance?download_url=https%3A%2F%2Flf3-package.vlabstatic.com%2Fobj%2Ffaceu-packages%2Finstaller%2Fjianying_jianyingpro_0_1.2.7_installer.exe&web_channel_level1=SEO&web_channel_level2=quark&web_channel_level3=&web_channel_level4=&web_session_start_url=https%253A%252F%252Fwww.capcut.cn%252F&web_url=https%253A%252F%252Fwww.capcut.cn%252F&web_referrer=https%3A%2F%2Fwww.quark.cn%2Fs%3Ffrom%3Dkkframenew_resultsearch%26uc_param_str%3Dntnwvepffrbiprsvchutosstxs%26by%3Dsubmit%26q%3D%25E5%2589%25AA%25E6%2598%25A0%26queryId%3D1tmZyX8tttaGTtNuuKDyns6OAhPqGLJXNvBh6gtihVOzLeh32A5KXwf9169634ac1e4#",
    "123云盘": "https://app.123pan.com/pc-pro/windows/231/123pan_2.3.1.exe",
    "Chrome浏览器": r"https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B3160C69B-E4E6-284D-B9DF-CB57A8673EDE%7D%26lang%3Dzh-CN%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-statsdef_1%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe",
    "VeraCrypt": "https://launchpad.net/veracrypt/trunk/1.26.20/+download/VeraCrypt%20Setup%201.26.20.exe",
    "Microsoft Edge(Canary)": "https://c2rsetup.edog.officeapps.live.com/c2r/downloadEdge.aspx?platform=Default&source=EdgeInsiderPage&Channel=Canary&language=zh-cn&brand=M103",
    "Dism++": "",
    "搜狗输入法": "https://ime-sec.gtimg.com/202502242307/f1b5369847fb2afaa2761f29864eb62c/pc/sogou_pinyin_guanwang_15.2a.exe",
    "IDM": "https://cpv2.mairuan.com/idmchina.net/full/idman642.exe",
    "WinNtsetup": "https://wntsetup.ru/WinNTSetup.zip",
    "WinRAR": "https://www.winrar.com.cn/download/winrar-x64-701scp.exe",
    "Bandizip": "https://bandisoft.okconnect.cn/bandizip/BANDIZIP-SETUP-STD-X64.EXE",
    "FastCopy": "https://pcshare.ddooo.com/file/fastcopy_91416.zip",
    "UltraISO": "https://www.ultraiso.net/uiso9_cn.exe",
    "Notepad++": "https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v8.7.7/npp.8.7.7.Installer.exe",
    "CPU-Z": "https://www.cpuid.com/downloads/cpu-z/cpu-z_2.14-cn.exe",
    "GPU-Z": "https://us8-dl.techpowerup.com/files/C-aHQWVBWTNepD5I9Vjm6g/1740453495/GPU-Z.2.63.0.exe",
    "360极速浏览器": "https://down.360safe.com/cse/360csex_setup.exe",
    "夸克浏览器": "https://umcdn.quark.cn/download/37212/quarkpc/pcquark@homepage_oficial/QuarkPC_V2.1.0.234_pc_pf30002_(zh-cn)_release_(Build2086145-250219204913-x64).exe",
    "百度网盘": "https://8f5d79-704917775.antpcdn.com:19001/b/pkg-ant.baidu.com/issue/netdisk/yunguanjia/BaiduNetdisk_7.52.0.135.exe",
    "PuTTY": "https://the.earth.li/~sgtatham/putty/latest/w64/putty-64bit-0.83-installer.msi",
    "FixWin": "",
    "图吧工具箱": r"https://download.tualatin.club/%E5%9B%BE%E5%90%A7%E5%B7%A5%E5%85%B7%E7%AE%B12025.02%E5%AE%89%E8%A3%85%E7%A8%8B%E5%BA%8F.exe",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
    "": "",
}
def yiyan_new():
    logging.debug('Send a request to [https://v1.hitokoto.cn/].')
    logging.debug('The [yiyan_new] function has been invoked.')
    global tttt
    response = requests.get(tttt)
    data = response.json()
    yiyan = data['hitokoto']
    zuozhe = data['from_who']
    chuzi = '《' + data['from'] + '》'
    if zuozhe is None:
        zuozhe = '佚名'
    if chuzi is None:
        chuzi = '未知'
    return yiyan + '————' + zuozhe + chuzi
def gushi():
    logging.debug('The [gushi] function has been invoked.')
    logging.debug('Send a request to [https://v1.jinrishici.com/all.json].')
    global ttt
    response = requests.get(ttt)
    data = response.json()
    gushi = data['content']
    zuozhe = data['author']
    mingzi = '《' + data['origin'] + '》'
    return gushi + '————' + zuozhe + mingzi
def is_windows_10_22h2_or_higher():
    logging.debug('The [is_windows_10_22h2_or_higher] function has been invoked.')
    version = platform.version()
    major, minor, build = version.split('.')
    return int(build) >= 19045
def is_windows_11_or_higher():
    logging.debug('The [is_windows_11_or_higher] function has been invoked.')
    version = platform.version()
    major, minor, build = version.split('.')
    return int(major) > 10 or (int(major) == 10 and int(build) >= 22000)
def cls():
    logging.debug('The [cls] function has been invoked.')
    os.system('cls')
def pause():
    logging.debug('The [pause] function has been invoked.')
    os.system('pause')
def cmd(x):
    logging.debug('The [cmd] function has been invoked.')
    os.system(x)
def Warning_1(x):
    logging.debug('The [Warning_1] function has been invoked.')
    print(f'\033[4;31m{x}\033[0m')
def zifu(x):
    logging.debug('The [zifu] function has been invoked.')
    x1 = ['/', '|', '\\', '-']
    for i in range(x):
        for i1 in x1:
            print(f"\r{i1}", end="") 
            time.sleep(0.1)
def dfd(password=str, text=str):
    logging.debug('The [dfd] function has been invoked.')
    if password == text:
        return True
    else:
        return False
def file_exists(filename):
    logging.debug('The [file_exists] function has been invoked.')
    return os.path.exists(filename)
def read_value(key):
    logging.debug('The [read_value] function has been invoked.')
    filename = 'user.wqt'
    try:
        with open(filename, 'r') as file:
            content = file.read().strip()
            if not content:
                print(f"文件 {filename} 内容为空。")
                return None
            data = ast.literal_eval(content)
            return data.get(key)
    except PermissionError:
        print(f"文件 {filename} 权限不足。")
        return None
    except (ValueError, SyntaxError) as e:
        print(f"文件格式错误: {e}")
        return None
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return None
cls()
cmd('chcp 65001')
class TextEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("WinQuickTools内置文本编辑器")
        self.root.geometry("600x400")
        self.text_area = scrolledtext.ScrolledText(self.root, wrap=tk.WORD, bg='#2c3e50', fg='white')
        self.text_area.pack(fill=tk.BOTH, expand=True)
        self.default_font = Font(family="黑体", size=12)
        self.text_area.configure(font=self.default_font)
        self.menu = tk.Menu(self.root, bg='#34495e', fg='white')
        self.root.config(menu=self.menu)
        self.file_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="文件", menu=self.file_menu)
        self.file_menu.add_command(label="新建", command=self.new_file)
        self.file_menu.add_command(label="打开", command=self.open_file)
        self.file_menu.add_command(label="保存", command=self.save_file)
        self.file_menu.add_command(label="另存为", command=self.save_as_file)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="退出", command=root.quit)
        self.edit_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="编辑", menu=self.edit_menu)
        self.edit_menu.add_command(label="撤销", command=self.text_area.edit_undo)
        self.edit_menu.add_command(label="重做", command=self.text_area.edit_redo)
        self.edit_menu.add_separator()
        self.edit_menu.add_command(label="剪切", command=self.cut_text)
        self.edit_menu.add_command(label="复制", command=self.copy_text)
        self.edit_menu.add_command(label="粘贴", command=self.paste_text)
        self.edit_menu.add_command(label="全选", command=self.select_all)
        self.edit_menu.add_command(label="日期", command=self.insert_date)
        self.edit_menu.add_separator()
        self.edit_menu.add_command(label="使用 Bing 搜索", command=self.search_with_bing)
        self.edit_menu.add_command(label="查找", command=self.find_text)
        self.edit_menu.add_command(label="查找下一个", command=lambda: self.find_text(forward=True))
        self.edit_menu.add_command(label="查找上一个", command=lambda: self.find_text(forward=False))
        self.format_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="格式", menu=self.format_menu)
        self.format_menu.add_command(label="自动换行", command=self.toggle_wrap)
        self.format_menu.add_command(label="字体", command=self.change_font)
        self.view_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="查看", menu=self.view_menu)
        self.view_menu.add_command(label="放大", command=self.zoom_in)
        self.view_menu.add_command(label="缩小", command=self.zoom_out)
        self.view_menu.add_command(label="恢复默认缩放", command=self.reset_zoom)
        self.view_menu.add_separator()
        self.status_bar_var = tk.BooleanVar()
        self.status_bar_var.set(True)
        self.view_menu.add_checkbutton(label="状态栏", variable=self.status_bar_var, command=self.toggle_status_bar)
        self.autosave_var = tk.BooleanVar()
        self.autosave_var.set(True)
        self.view_menu.add_checkbutton(label="自动保存", variable=self.autosave_var, command=self.toggle_autosave)
        self.help_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="帮助", menu=self.help_menu)
        self.help_menu.add_command(label="查看帮助", command=self.view_help)
        self.help_menu.add_command(label="发送反馈", command=self.send_feedback)
        self.help_menu.add_command(label="关于文本编辑器", command=self.about_editor)
        self.search_text = ""
        self.search_tags = []
        self.file_encoding = "UTF-8"
        self.filename = None
        self.status_bar = tk.Label(self.root, text="就绪", bg='#34495e', fg='white')
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        self.text_area.bind('<KeyRelease>', self.update_status_bar)
        self.text_area.bind('<ButtonRelease-1>', self.update_status_bar)
        self.text_area.bind('<MouseWheel>', self.update_status_bar)
        self.text_area.bind('<Button-4>', self.update_status_bar)
        self.text_area.bind('<Button-5>', self.update_status_bar)
        self.root.bind('<Configure>', self.update_status_bar)
        self.update_status_bar()
        self.last_saved_content = self.text_area.get(1.0, tk.END)
        self.autosave_interval = 60000  # 60 seconds
        self.root.after(self.autosave_interval, self.autosave)
        self.add_encrypt_menu()

    def add_encrypt_menu(self):
        self.encrypt_menu = tk.Menu(self.menu, tearoff=0, bg='#34495e', fg='white')
        self.menu.add_cascade(label="加密", menu=self.encrypt_menu)
        self.encrypt_menu.add_command(label="加密文件", command=self.encrypt_file)
        self.encrypt_menu.add_command(label="解密文件", command=self.decrypt_file)

    def encrypt_file(self):
        file_path = filedialog.askopenfilename()
        if not file_path:
            return
        key = get_random_bytes(16)  # AES key must be either 16, 24, or 32 bytes long
        self.show_progress_window("正在加密文件，请稍候...")
        threading.Thread(target=self._encrypt_file, args=(file_path, key)).start()

    def _encrypt_file(self, file_path, key):
        try:
            cipher = AES.new(key, AES.MODE_CBC)
            with open(file_path, 'rb') as file:
                data = file.read()
            encrypted_data = cipher.encrypt(pad(data, AES.block_size))
            encrypted_file_path = file_path + ".enc"
            with open(encrypted_file_path, 'wb') as file:
                file.write(cipher.iv + encrypted_data)
            with open("key.txt", "w") as key_file:  # Save key as hex string
                key_file.write(key.hex())
            self.hide_progress_window()
            messagebox.showinfo("加密成功", f"文件已加密并保存为 {encrypted_file_path}\n密钥已保存到 key.txt")
        except Exception as e:
            self.hide_progress_window()
            messagebox.showerror("加密错误", str(e))

    def decrypt_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("Encrypted Files", "*.enc"), ("All Files", "*.*")])
        if not file_path:
            return
        key = simpledialog.askstring("解密文件", "请输入密钥：")
        if not key:
            return
        key = bytes.fromhex(key)
        self.show_progress_window("正在解密文件，请稍候...")
        threading.Thread(target=self._decrypt_file, args=(file_path, key)).start()

    def _decrypt_file(self, file_path, key):
        try:
            with open(file_path, 'rb') as file:
                iv = file.read(16)  # AES block size is 16 bytes
                encrypted_data = file.read()
            cipher = AES.new(key, AES.MODE_CBC, iv)
            decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)
            decrypted_file_path = file_path.replace(".enc", "")
            with open(decrypted_file_path, 'wb') as file:
                file.write(decrypted_data)
            self.hide_progress_window()
            messagebox.showinfo("解密成功", f"文件已解密并保存为 {decrypted_file_path}")
        except Exception as e:
            self.hide_progress_window()
            messagebox.showerror("解密错误", str(e))

    def show_progress_window(self, message):
        self.progress_window = Toplevel(self.root)
        self.progress_window.title("请稍候")
        self.progress_window.geometry("300x100")
        self.progress_window.transient(self.root)
        self.progress_window.grab_set()
        self.progress_label = tk.Label(self.progress_window, text=message)
        self.progress_label.pack(pady=20)

    def hide_progress_window(self):
        if self.progress_window:
            self.progress_window.destroy()

    def new_file(self):
        if self.text_area.get(1.0, tk.END).strip() != "" and self.filename is None:
            save_changes = messagebox.askyesnocancel("新建文件", "当前文件有内容但未保存，是否保存？")
            if save_changes is None:
                return
            elif save_changes:
                self.save_file()
        self.text_area.delete(1.0, tk.END)
        self.filename = None
        self.file_encoding = "UTF-8"
        self.update_status_bar()

    def open_file(self):
        self.filename = filedialog.askopenfilename(defaultextension=".txt",
                                                   filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")])
        if self.filename:
            with open(self.filename, 'r', encoding='utf-8') as file:
                content = file.read()
                self.text_area.delete(1.0, tk.END)
                self.text_area.insert(tk.INSERT, content)
            self.file_encoding = "UTF-8"
            self.update_status_bar()

    def save_file(self):
        if not self.filename:
            self.save_as_file()
        else:
            self.save_file_with_encoding(self.filename, self.file_encoding)

    def save_as_file(self):
        self.filename = filedialog.asksaveasfilename(defaultextension=".txt",
                                                     filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")])
        if self.filename:
            encoding = simpledialog.askstring("保存文件", "请输入编码（如 UTF-8, GBK, GB2312, ASCII）：", initialvalue="UTF-8")
            if encoding:
                self.file_encoding = encoding
                self.save_file_with_encoding(self.filename, self.file_encoding)

    def save_file_with_encoding(self, filename, encoding):
        try:
            with open(filename, 'w', encoding=encoding) as file:
                content = self.text_area.get(1.0, tk.END)
                file.write(content)
        except Exception as e:
            messagebox.showerror("保存文件错误", str(e))
        self.update_status_bar()

    def cut_text(self):
        self.text_area.event_generate(("<<Cut>>"))

    def copy_text(self):
        self.text_area.event_generate(("<<Copy>>"))

    def paste_text(self):
        self.text_area.event_generate(("<<Paste>>"))

    def select_all(self):
        self.text_area.tag_add(tk.SEL, "1.0", tk.END)
        self.text_area.mark_set(tk.INSERT, "1.0")
        self.text_area.see(tk.INSERT)

    def insert_date(self):
        current_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.text_area.insert(tk.INSERT, current_date)

    def search_with_bing(self):
        selected_text = self.text_area.get(tk.SEL_FIRST, tk.SEL_LAST)
        if selected_text:
            webbrowser.open(f"https://cn.bing.com/search?q={selected_text}")

    def find_text(self, forward=True):
        if not self.search_text:
            self.search_text = simpledialog.askstring("查找", "请输入要查找的文本：")
            if not self.search_text:
                return
        self.clear_search_tags()
        start_pos = "1.0" if forward else "end-1c"
        pos = self.text_area.search(self.search_text, start_pos, forwards=forward, nocase=True)
        if not pos:
            messagebox.showinfo("查找", "未找到匹配的文本")
            self.search_text = ""
            return
        self.text_area.tag_add("search", pos, f"{pos}+{len(self.search_text)}c")
        self.text_area.tag_config("search", background="yellow")
        self.search_tags.append("search")
        self.text_area.see(pos)

    def clear_search_tags(self):
        for tag in self.search_tags:
            self.text_area.tag_remove(tag, "1.0", tk.END)
        self.search_tags.clear()

    def toggle_wrap(self):
        wrap_mode = self.text_area.cget("wrap")
        new_wrap_mode = tk.NONE if wrap_mode == tk.WORD else tk.WORD
        self.text_area.config(wrap=new_wrap_mode)

    def change_font(self):
        fonts = sorted(list(font.families()))
        selected_font = self.default_font.cget("family")
        self.font_window = tk.Toplevel(self.root)
        self.font_window.title("选择字体")
        self.font_window.geometry("300x400")
        self.font_search_var = tk.StringVar()
        self.font_search_var.trace_add("write", self.filter_fonts)
        self.font_search_entry = tk.Entry(self.font_window, textvariable=self.font_search_var)
        self.font_search_entry.pack(side=tk.TOP, fill=tk.X)
        self.font_listbox = tk.Listbox(self.font_window)
        self.font_listbox.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        self.font_scrollbar = tk.Scrollbar(self.font_window, orient=tk.VERTICAL, command=self.font_listbox.yview)
        self.font_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.font_listbox.config(yscrollcommand=self.font_scrollbar.set)
        for font_name in fonts:
            self.font_listbox.insert(tk.END, font_name)
        self.font_listbox.select_set(fonts.index(selected_font))
        self.font_listbox.bind("<Double-1>", self.apply_font)
        self.font_window.transient(self.root)
        self.font_window.grab_set()
        self.root.wait_window(self.font_window)

    def filter_fonts(self, *args):
        search_term = self.font_search_var.get().lower()
        self.font_listbox.delete(0, tk.END)
        for font_name in sorted(list(font.families())):
            if search_term in font_name.lower():
                self.font_listbox.insert(tk.END, font_name)

    def apply_font(self, event=None):
        selected_font = self.font_listbox.get(self.font_listbox.curselection())
        self.default_font.configure(family=selected_font)
        self.text_area.configure(font=self.default_font)
        self.font_window.destroy()
        self.update_status_bar()

    def zoom_in(self):
        current_size = self.default_font.cget("size")
        self.default_font.configure(size=current_size + 2)
        self.text_area.configure(font=self.default_font)
        self.update_status_bar()

    def zoom_out(self):
        current_size = self.default_font.cget("size")
        self.default_font.configure(size=current_size - 2)
        self.text_area.configure(font=self.default_font)
        self.update_status_bar()

    def reset_zoom(self):
        self.default_font.configure(size=12)
        self.text_area.configure(font=self.default_font)
        self.update_status_bar()

    def toggle_status_bar(self):
        if self.status_bar_var.get():
            self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        else:
            self.status_bar.pack_forget()

    def update_status_bar(self, event=None):
        cursor_pos = self.text_area.index(tk.INSERT)
        row, col = cursor_pos.split('.')
        zoom_size = self.default_font.cget("size")
        if self.filename:
            status_text = f"文件名：{self.filename} | 编码：{self.file_encoding} | 缩放：{zoom_size} | 行：{row} | 列：{col}"
        else:
            status_text = f"编码：{self.file_encoding} | 缩放：{zoom_size} | 行：{row} | 列：{col}"
        self.status_bar.config(text=status_text)

    def view_help(self):
        messagebox.showinfo("帮助", "")

    def send_feedback(self):
        webbrowser.open("mailto:WinQuickTools@163.com?subject=反馈")

    def about_editor(self):
        messagebox.showinfo("关于文本编辑器", "WinQuickTools内置文本编辑器\n版本 1.0\n作者：pmx1119")

    def autosave(self):
        if not self.autosave_var.get():
            return
        current_content = self.text_area.get(1.0, tk.END)
        if current_content != self.last_saved_content and self.filename:
            self.save_file_with_encoding(self.filename, self.file_encoding)
            self.last_saved_content = current_content
        self.root.after(self.autosave_interval, self.autosave)

    def toggle_autosave(self):
        if self.autosave_var.get():
            self.root.after(self.autosave_interval, self.autosave)
        else:
            self.root.after_cancel(self.autosave)
def start_TextEditor():
    root = tk.Tk()
    app = TextEditor(root)
    root.mainloop()
def start_wqt():
    def user_info(info=str):
        logging.basicConfig(level=logging.DEBUG, filename='wqt.log', filemode='a', format='[%(asctime)s %(name)s %(levelname)s]: %(message)s', datefmt='%Y/%m/%d/%H:%M:%S')
        logging.info(info)
    def error_unknown():
        logging.debug('The [error_unknown] function has been invoked.')
        print('\033[4;31m ERROR CODE:unknown 未知的命令\033[0m')
    def Warning(x):
        logging.debug('The [Warning] function has been invoked.')
        print(f'\033[4;31m{x}\033[0m')
    def cmd(x):
        logging.debug('The [cmd] function has been invoked.')
        os.system(x)
    def powershell():
        logging.debug('The [powershell] function has been invoked.')
        os.system('powershell')
    def getFonts(self):
        logging.debug('The [getFonts] function has been invoked.')
        return self.Font.getFonts()
    def add(n1 , n2):
        logging.debug('The [add] function has been invoked.')
        v = int(n1)
        v2 = int(n2)
        n3 = v + v2
        print(n3)
    def subtract(n1 , n2):
        logging.debug('The [subtract] function has been invoked.')
        v = int(n1)
        v2 = int(n2)
        n3 = v - v2
        print(n3)
    def multiply(n1 , n2):
        logging.debug('The [multiply] function has been invoked.')
        v = int(n1)
        v2 = int(n2)
        n3 = v * v2
        print(n3)
    def divide(n1 ,n2):
        logging.debug('The [divide] function has been invoked.')
        v = int(n1)
        v2 = int(n2)
        n3 = v / v2
        print(n3)
    def square_root(x):
        logging.debug('The [square_root] function has been invoked.')
        float(x)
        y = math.sqrt(x)
        print('{x}的平方根是：{y}')
    def Exponentiation(x, y):
        logging.debug('The [Exponentiation] function has been invoked.')
        float(x)
        float(y)
        z = math.pow(x, y)
        print(f'{x}的{y}次方是：{z}')
    def solve_equations(x, y, z):
        logging.debug('The [solve_equations] function has been invoked.')
        float(y)
        float(z)
        x1 = sp.Eq(y, z)
        x2 = sp.solve(x1, x)
        return sp.solve(x1, x)
    def Rectangular_area(x, y):
        logging.debug('The [Rectangular_area] function has been invoked.')
        float(x)
        float(y)
        return x * y
    def Triangle_area(x, y):
        logging.debug('The [Triangle_area] function has been invoked.')
        float(x)
        float(y)
        return x * y / 2
    def Square_area(x):
        logging.debug('The [Square_area] function has been invoked.')
        return x ** 2
    def Circle_area(x):
        logging.debug('The [Circle_area] function has been invoked.')
        float(x)
        return math.pi * x
    def Trapezoidal_area(x, y, z):
        logging.debug('The [Trapezoidal_area] function has been invoked.')
        float(x)
        float(y)
        float(z)
        return (x + y) * z / 2
    def Rectangular_volume(x, y, z):
        logging.debug('The [Rectangular_volume] function has been invoked.')
        float(x)
        float(y)
        float(z)
        return x * y * z
    def Square_volume(x):
        logging.debug('The [Square_volume] function has been invoked.')
        float(x)
        return x ** 3
    def triangular_prism_volume(x, y, z):
        logging.debug('The [triangular_prism_volume] function has been invoked.')
        float(x)
        float(y)
        float(z)
        return x * y / 2 * z
    def Triangular_pyramid_volume(x, y, z):
        logging.debug('The [Triangular_pyramid_volume] function has been invoked.')
        float(x)
        float(y)
        float(z)
        x1 = x * y / 2
        return 1 / 3 * x1 * z
    def Spherical_volume(x):
        logging.debug('The [Spherical_volume] function has been invoked.')
        float(x)
        x1 = 4 / 3
        pi = math.pi
        x2 = x ** 3
        return x1 * pi * x2
    def callback(a1, a2, a3):
        logging.debug('The [callback] function has been invoked.')
        download_pg = 100.0 * a1 * a2 / a3
        if download_pg > 100:
            download_pg = 100
        print('%.2f%%' % download_pg)
    def generate_password_1_a_A_bit(length):
        logging.debug('The [generate_password_1_a_A_bit] function has been invoked.')
        characters = string.ascii_letters + string.digits + string.punctuation
        password = [random.choice(characters) for _ in range(length)]
        random.shuffle(password)
        password_str = ''.join(password)
        return password_str
    def generate_password_1_a_A(length):
        logging.debug('The [generate_password_1_a_A] function has been invoked.')
        characters = string.ascii_letters + string.digits
        password = [random.choice(characters) for _ in range(length)]
        random.shuffle(password)
        password_str = ''.join(password)
        return password_str
    def generate_password_1_a(length=12):
        logging.debug('The [generate_password_1_a] function has been invoked.')
        characters = string.ascii_lowercase + string.digits
        password = [random.choice(characters) for _ in range(length)]
        random.shuffle(password)
        password_str = ''.join(password)
        return password_str
    def generate_password(length=12):
        logging.debug('The [generate_password] function has been invoked.')
        characters = string.digits
        password = [random.choice(characters) for _ in range(length)]
        random.shuffle(password)
        password_str = ''.join(password)
        return password_str
    def search_file(directory, filename):#搜索
        logging.debug('The [search_file] function has been invoked.')
        for root, dirs, files in os.walk(directory):
            if filename in files:
                        print(os.path.join(root, filename))
    def compare_files(file1, file2):# 比较文件
        logging.debug('The [compare_files] function has been invoked.')
        with open(file1, 'r') as f1, open(file2, 'r') as f2:
            lines1 = f1.readlines()
            lines2 = f2.readlines()
        for i, (l1, l2) in enumerate(zip(lines1, lines2)):
            if l1 != l2:
                print(f"Line {i + 1}:")
                print(f"File 1: {l1.strip()}")
                print(f"File 2: {l2.strip()}")
    def merge_files(directory, output_file):
        logging.debug('The [merge_files] function has been invoked.')
        with open(output_file, 'w') as outfile:
            for root, dirs, files in os.walk(directory):
                for file in files:
                    if file.endswith('.txt'):#合并
                        with open(os.path.join(root, file), 'r') as infile:
                            content = infile.read()
                            outfile.write(content)
                            outfile.write('\n') 
    def list_installed_software():#软件集
        logging.debug('The [list_installed_software] function has been invoked.')
        software_list = subprocess.check_output("wmic product get name", shell=True, text=True)
        software_list = software_list.split('\n')
        for software in software_list:
            print(software.strip())
    def uninstall_software(software_name):#卸载
        logging.debug('The [uninstall_software] function has been invoked.')
        subprocess.run(f"wmic product where name='{software_name}' call uninstall", shell=True)
    def list_processes():
        logging.debug('The [list_processes] function has been invoked.')
        processes = subprocess.check_output("tasklist /fo table /v", shell=True, text=True)
        processes = processes.split('\n')
        for process in processes[3:]:
            print(process)
    def kill_process(pid):
        logging.debug('The [kill_process] function has been invoked.')
        subprocess.run(f"taskkill /pid {pid} /f", shell=True)
    def read_file(filename):
        logging.debug('The [read_file] function has been invoked.')
        with open(filename, "r") as file:
            content = file.read()
        return content
    def write_file(filename, content):
        logging.debug('The [write_file] function has been invoked.')
        with open(filename, "w") as file:
            file.write(content)
    def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=50, fill='\033[1;34m▉\033[0m', print_end="\r"):
        logging.debug('The function [print_progress_bar] has been created.')
        percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
        filled_length = int(length * iteration // total)
        bar = fill * filled_length + '▉' * (length - filled_length)
        print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=print_end)
        if iteration == total: 
            print()
    def unzip_file(zip_path, dest_path):
        logging.debug('The [unzip_file] function has been invoked.')
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(dest_path)
    def run_rufus():
        logging.debug('The [run_rufus] function has been invoked.')
        current_dir = os.path.dirname(os.path.abspath(__file__))
        zip_path = os.path.join(current_dir, "Rufus.zip")
        if not os.path.exists(zip_path):
            logging.error('Not found file!')
            print("没有找到库！请检查库文件名称和路径是否正确！")
            return
        temp_dir = tempfile.mkdtemp()
        unzip_path = temp_dir + "\\Rufus"
        unzip_file(zip_path, unzip_path)
        Rufus_path = os.path.join(unzip_path, "Rufus.exe")
        if not os.path.exists(Rufus_path):
            logging.error('Not found file!')
            print("库文件已损坏！请检查库完整性或到官网重新下载！")
            return
        os.system(f"start {Rufus_path}")
    def run_cmd():
        logging.debug('The [run_cmd] function has been invoked.')
        current_dir = os.path.dirname(os.path.abspath(__file__))
        zip_path = os.path.join(current_dir, "cmd.zip")
        if not os.path.exists(zip_path):
            logging.error('Not found file!')
            print("没有找到库！请检查库文件名称和路径是否正确！")
            return
        temp_dir = tempfile.mkdtemp()
        unzip_path = temp_dir + "\\cmd"
        unzip_file(zip_path, unzip_path)
        Rufus_path = os.path.join(unzip_path, "cmd.exe")
        if not os.path.exists(Rufus_path):
            logging.error('Not found file!')
            print("库文件已损坏！请检查库完整性或到官网重新下载！")
            return
        os.system(f"start {Rufus_path}")
    def run_powershell():
        logging.debug('The [run_powershell] function has been invoked.')
        current_dir = os.path.dirname(os.path.abspath(__file__))
        zip_path = os.path.join(current_dir, "powershell.zip")
        if not os.path.exists(zip_path):
            logging.error('Not found file!')
            print("没有找到库！请检查库文件名称和路径是否正确！")
            return
        temp_dir = tempfile.mkdtemp()
        unzip_path = temp_dir + "\\powershell"
        unzip_file(zip_path, unzip_path)
        Rufus_path = os.path.join(unzip_path, "powershell.exe")
        if not os.path.exists(Rufus_path):
            logging.error('Not found file!')
            print("库文件已损坏！请检查库完整性或到官网重新下载！")
            return
        os.system(f"start {Rufus_path}")
    def run_Win11():
        logging.debug('The [run_Win11] function has been invoked.')
        current_dir = os.path.dirname(os.path.abspath(__file__))
        for file in os.listdir(current_dir):
            if file == "Win11_OOBE.zip":
                zip_path = os.path.join(current_dir, file)
                break
        if not os.path.exists(zip_path):
            logging.error('Not found file!')
            print("没有找到库！请检查库文件名称和路径是否正确！")
            return
        temp_dir = tempfile.mkdtemp()
        unzip_path = os.path.join(temp_dir, "Win11_OOBE")
        unzip_file(zip_path, unzip_path)
        sysprep_path = os.path.join(unzip_path, "sysprep.exe")
        if not os.path.exists(sysprep_path):
            logging.error('Not found file!')
            print("库文件已损坏！请检查库完整性或到官网重新下载！")
            return
        os.system(f"start {sysprep_path}")
    def disable_windows_update():
        logging.debug('The [disable_windows_update] function has been invoked.')
        try:
            os.system('net stop wuauserv')
            os.system('sc config wuauserv start= disabled')
            os.system('del /f /q C:\\Windows\\System32\\wuapi.dll')
            os.system('del /f /q C:\\Windows\\System32\\wuauclt.exe')
            os.system('del /f /q C:\\Windows\\System32\\wuauserv.exe')
            os.system('reg add "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\WindowsUpdate\\UX\\Settings"/vFlightSettingsMaxPauseDays /t reg_dwrod /d 5000 /f')
            print("Windows更新已关闭。")
        except Exception as e:
            logging.error('Error occurred while disabling Windows update')
            print("关闭Windows更新时出错：", e)
    def yiyan():
        logging.debug('The [yiyan] function has been invoked.')
        response = requests.get('https://v.api.aa1.cn/api/yiyan/index.php')
        data = response.json()
        return data
    def Internet():
        logging.debug('The [Internet] function has been invoked.')
        url = "https://sunzishaokao.com"
        url1 = "https://www.baidu.com"
        url2 = "https://www.360.com"
        timeout = 5
        try:
            requests.head(url, timeout=timeout)
            return True
        except requests.ConnectionError:
            try:
                requests.head(url1, timeout=timeout)
                return True
            except requests.ConnectionError:
                try:
                    requests.head(url2, timeout=timeout)
                    return True
                except requests.ConnectionError:
                    return False
    def test_website(website, concurrency, duration):
        def fetch_url(url):
            try:
                response = requests.get(url)
                return response.status_code
            except requests.RequestException as e:
                return e
        start_time = time.time()
        with ThreadPoolExecutor(max_workers=concurrency) as executor:
            futures = [executor.submit(fetch_url, website) for _ in range(concurrency)]
            while time.time() - start_time < duration:
                for future in as_completed(futures):
                    status = future.result()
                    print(f"请求完成，状态码: {status}")
                    futures.remove(future)
                    futures.append(executor.submit(fetch_url, website))
            for future in futures:
                future.cancel()
    def test_network_speed():
        st = speedtest.Speedtest()
        st.get_best_server()
        download_speed = st.download()
        print(f"下载速度: {download_speed / 1024 / 1024:.2f} Mbps")
        upload_speed = st.upload()
        print(f"上传速度: {upload_speed / 1024 / 1024:.2f} Mbps")
        ping = st.results.ping
        print(f"Ping: {ping} ms")
    def display_all_hardware_info():
        try:
            c = wmi.WMI()
            print("CPU信息:")
            for cpu in c.Win32_Processor():
                print(f"  名称: {cpu.Name}, 核心数: {cpu.NumberOfCores}, 线程数: {cpu.ThreadCount}")
            print("\n内存信息:")
            for ram in c.Win32_PhysicalMemory():
                print(f"  容量: {ram.Capacity} 字节")
            print("\n硬盘信息:")
            for disk in c.Win32_DiskDrive():
                print(f"  设备ID: {disk.DeviceID}, 接口类型: {disk.InterfaceType}, 大小: {disk.Size} 字节")
            print("\n显卡信息:")
            for gpu in c.Win32_VideoController():
                print(f"  名称: {gpu.Name}, 驱动版本: {gpu.DriverVersion}")
            print("\n网络适配器信息:")
            for nic in c.Win32_NetworkAdapter():
                print(f"  描述: {nic.Description}, MAC地址: {nic.MACAddress}")
            print("\n声卡信息:")
            for sound in c.Win32_SoundDevice():
                print(f"  名称: {sound.Name}")
            print("\n显示器信息:")
            for monitor in c.Win32_DesktopMonitor():
                print(f"  描述: {monitor.Description}")
            print("\nBIOS信息:")
            for bios in c.Win32_BIOS():
                print(f"  制造商: {bios.Manufacturer}, 版本: {bios.Version}")
            print("\n主板信息:")
            for board in c.Win32_BaseBoard():
                print(f"  制造商: {board.Manufacturer}, 产品: {board.Product}")
        except Exception as e:
            logging.error("An error occurred while retrieving hardware information.")
            print(f"获取硬件信息时发生错误: {e}")
    def display_cpu_info():
        logging.debug('The function [display_cpu_info] has been created.')
        try:
            cpu_info = {}
            cpu_info['logical_cores'] = psutil.cpu_count(logical=True)
            cpu_info['physical_cores'] = psutil.cpu_count(logical=False)
            cpu_freq = psutil.cpu_freq()
            cpu_info['current_frequency'] = cpu_freq.current
            cpu_info['max_frequency'] = cpu_freq.max
            cpu_info['min_frequency'] = cpu_freq.min
            cpu_info['architecture'] = platform.processor()
            cpu_stats = psutil.cpu_stats()
            cpu_info['ctx_switches'] = cpu_stats.ctx_switches
            cpu_info['interrupts'] = cpu_stats.interrupts
            cpu_info['soft_interrupts'] = cpu_stats.soft_interrupts
            cpu_info['syscalls'] = cpu_stats.syscalls
            per_cpu_usage = psutil.cpu_percent(interval=1, percpu=True)
            cpu_info['per_cpu_usage'] = per_cpu_usage
            info_dict = {
                "logical_cores": "逻辑核心数",
                "physical_cores": "物理核心数",
                "current_frequency": "当前频率(MHz)",
                "max_frequency": "最大频率(MHz)",
                "min_frequency": "最小频率(MHz)",
                "architecture": "CPU架构",
                "ctx_switches": "上下文切换次数",
                "interrupts": "中断次数",
                "soft_interrupts": "软中断次数",
                "syscalls": "系统调用次数",
                "per_cpu_usage": "每个核心的使用率(%)"
            }
            for key, value in cpu_info.items():
                print(f"{info_dict[key]}: {value}")
            result = subprocess.run(['wmic', 'cpu', 'get', 'name,NumberOfCores,NumberOfLogicalProcessors'], stdout=subprocess.PIPE)
            detailed_info = result.stdout.decode('gbk').strip()
            detailed_info_lines = detailed_info.split('\n')[1:]
            print("\n详细的CPU信息:")
            for line in detailed_info_lines:
                print(line)
            result = subprocess.run(['wmic', 'path', 'win32_temperaturesensor', 'get', 'currentreading'], stdout=subprocess.PIPE)
            cpu_temperature = result.stdout.decode('gbk').strip()
        except Exception as e:
            logging.error("An error occurred while retrieving CPU information.")
            print(f"获取CPU信息时发生错误: {e}")
    def NTFS(x):
        try:
            cmd(f'format {x} /FS:NTFS /Q')
            print("格式化成功。")
            pause()
            cls()
        except:
            logging.error('An error occurred while formatting the drive.')
            print("格式化失败，请检查磁盘是否可用。")
            pause()
    def FAT32(x):
        try:
            cmd(f'format {x} /FS:FAT32 /Q')
            print("格式化成功。")
            pause()
            cls()
        except:
            logging.error('An error occurred while formatting the drive.')
            print("格式化失败，请检查磁盘是否可用。")
            pause()
    def exFAT(x):
        try:
            cmd(f'format {x} /FS:exFAT /Q')
            print("格式化成功。")
            pause()
            cls()
        except:
            logging.error('An error occurred while formatting the drive.')
            print("格式化失败，请检查磁盘是否可用。")
            pause()
    def scan_bad_sectors_windows(drive_letter):
        try:
            result = subprocess.run(['chkdsk', drive_letter + ':', '/R'], capture_output=True, text=True, check=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error occurred: {e}")
    def pwsh(Commands):
        try:
            subprocess.run(["powershell", "-Command", Commands], check=True)
        except subprocess.CalledProcessError as e:
            print(f"Error occurred: {e}")
    def remove_defender():
        try:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            zip_path = os.path.join(current_dir, "remove_defender.zip")
            if not os.path.exists(zip_path):
                logging.error("No library files found!")
                print("没有找到库！请检查库文件名称和路径是否正确！")
                pause()
            temp_dir = tempfile.mkdtemp()
            unzip_path = temp_dir + "\\remove-defender"
            unzip_file(zip_path, unzip_path)
            remove_defender_path = os.path.join(unzip_path, "remove-defender.exe")
            if not os.path.exists(remove_defender_path):
                print("库文件已损坏！请检查库完整性或到官网重新下载！")
                pause()
            os.system(f"start {remove_defender_path}")
        except Exception as e:
            pwsh('Uninstall-WindowsFeature -Name Windows-Defender')
    def connect_to_wifi(ssid, password):
        try:
            command = f"netsh wlan connect name='{ssid}' ssid='{ssid}' key='{password}'"
            cmd(command)
            print(f'已连接到{ssid}网络。')
        except Exception as e:
            print(f'链接WiFi{ssid}失败,错误代码:{e}')
    def clean_temp_folder():
        temp_dir = r'C:\\Windows\\Temp'
        for filename in os.listdir(temp_dir):
            file_path = os.path.join(temp_dir, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                logging.error(f'Error deleting {file_path}. Error code: {e}')
                print(f'删除{file_path}时出错。错误代码:{e}')
    def download_file(url, filename=None):
        if filename is None:
            filename = url.split("/")[-1]
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            total_size = int(response.headers.get('content-length', 0))
            with open(filename, 'wb') as file, tqdm(
                desc=filename,
                total=total_size,
                unit='iB',
                unit_scale=True,
                unit_divisor=1024,
            ) as bar:
                for data in response.iter_content(chunk_size=1024):
                    size = file.write(data)
                    bar.update(size)
            print(f"文件已下载: {filename}")
        else:
            logging
            print(f"下载失败，状态码: {response.status_code}")
    def restore_right_click_menu():
        try:
            cmd('reg add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve')
            print("右键菜单已恢复。")
        except Exception as e:
            print(f"恢复右键菜单失败，错误代码:{e}")
    def windows_version():
        version = platform.version()
        major_version = int(version.split('.')[0])
        minor_version = int(version.split('.')[1])
        if major_version > 10:
            return True
        elif major_version == 10 and minor_version >= 22000:
            return True
        else:
            return False
    def Activate_Windows(secret_key, Version_Name=None):
        if Version_Name == None:
            cmd('slmgr /upk')
            cmd(f'slmgr -ipk {secret_key}')
            cmd('slmgr -skms kms.0t.net.cn')
            cmd('slmgr -ato')
        else:
            cmd('slmgr /upk')
            cmd(f'slmgr -ipk P36VD-22V68-JVM2W-DBC77-MK98W')
            cmd('slmgr -skms kms.0t.net.cn')
            cmd('slmgr -ato')
            print(f'已激活{Version_Name}')
    def query_domain(domain):
        try:
            w = whois.whois(domain)
            if w.domain_name:
                print(f"域名 {domain} 已被注册")
            else:
                print(f"域名 {domain} 未被注册")
        except whois.parser.PywhoisError:
            print(f"查询域名 {domain} 时出错")
    def get_domain_info(domain):
        try:
            w = whois.whois(domain)
            print(w)
        except whois.parser.PywhoisError:
            print(f"查询域名 {domain} 时出错")
    def check_port(host, port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.05) 
        result = sock.connect_ex((host, port))
        if result == 0:
            print(f"端口 {port} 是开放的")
        else:
            print(f"端口 {port} 是关闭的")
        sock.close()
    def scan_ports(host, start_port, end_port):
        for port in range(start_port, end_port + 1):
            check_port(host, port)
    def scan_ip(ip):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((ip, 80))
            if result == 0:
                print(f"IP地址 {ip} 是活跃的")
            sock.close()
        except Exception as e:
            print(f"扫描IP地址 {ip} 时发生错误：{e}")
    def scan_range(start_ip, end_ip):
        start = list(map(int, start_ip.split('.')))
        end = list(map(int, end_ip.split('.')))
        threads = []
        for i in range(start[0], end[0] + 1):
            for j in range(start[1], end[1] + 1):
                for k in range(start[2], end[2] + 1):
                    for l in range(start[3], end[3] + 1):
                        ip = f"{i}.{j}.{k}.{l}"
                        thread = threading.Thread(target=scan_ip, args=(ip,))
                        threads.append(thread)
                        thread.start()
        for thread in threads:
            thread.join()
    def get_and_print_lan_mac_addresses():
        try:
            result = subprocess.run(["arp", "-a"], capture_output=True, text=True, check=True)
            output = result.stdout
            mac_addresses = re.findall(r"([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})", output)
            for mac in set(mac_addresses):
                print(mac[0])
        except subprocess.CalledProcessError as e:
            print(f"执行arp命令时出错：{e}")
        except Exception as e:
            print(f"发生错误：{e}")
    logging.debug('The function [convert_image_to_ascii_art] has been created.')
    def convert_image_to_ascii_art():
        root = tk.Tk()
        root.withdraw()
        image_path = filedialog.askopenfilename()
        if not image_path:
            print("没有选择图片。")
            return
        try:
            image = Image.open(image_path)
            image = image.convert("L")
            target_width = 100
            target_height = 50
            image = image.resize((target_width, target_height), Image.ANTIALIAS)
            art_text = ascii_art(image, chars=" .:-=+*#%@")
            with open("image.txt", "w") as file:
                file.write(art_text)
            print("字符画已保存到image.txt")
        except Exception as e:
            print(f"处理图片时出错：{e}")
    def confirm_deletion(items, item_type):
        print(f"\n以下是要删除的 {item_type}：")
        for item in items:
            print(item)
        confirmation = input(f"是否确认删除这些 {item_type}？(y/n): ").strip().lower()
        return confirmation == 'y'
    def delete_files(files):
        if confirm_deletion(files, "文件"):
            for file in files:
                try:
                    os.remove(file)
                    print(f"Deleted: {file}")
                except Exception as e:
                    print(f"Error deleting {file}: {e}")
    def list_temp_files():
        temp_dir = os.getenv('TEMP')
        files_to_delete = []
        for foldername, subfolders, filenames in os.walk(temp_dir):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                files_to_delete.append(file_path)
        return files_to_delete
    def list_recycle_bin_files():
        recycle_bin_path = os.path.join(os.getenv('SystemDrive'), '$Recycle.Bin')
        files_to_delete = []
        for foldername, subfolders, filenames in os.walk(recycle_bin_path):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                files_to_delete.append(file_path)
        return files_to_delete
    def delete_registry_keys(keys):
        if confirm_deletion(keys, "注册表项"):
            for key in keys:
                try:
                    winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key)
                    print(f"Deleted registry key: {key}")
                except Exception as e:
                    print(f"Error deleting registry key {key}: {e}")
    def list_registry_keys():
        registry_path = r"Software\\Microsoft\\Windows\\CurrentVersion\\Run"
        registry_keys = []
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, registry_path, 0, winreg.KEY_READ) as key:
                i = 0
                while True:
                    try:
                        subkey_name = winreg.EnumKey(key, i)
                        registry_keys.append(os.path.join(registry_path, subkey_name))
                        i += 1
                    except OSError:
                        break
        except FileNotFoundError:
            print(f"Registry path not found: {registry_path}")
        return registry_keys
    def clean_and_list():
        temp_files = list_temp_files()
        delete_files(temp_files)
        recycle_bin_files = list_recycle_bin_files()
        delete_files(recycle_bin_files)
        registry_keys = list_registry_keys()
        delete_registry_keys(registry_keys)
    def is_encrypt_mode(mode):
        return "encrypt" in mode
    def encrypt_decrypt(text, mode, key=None, shift=None):
        """
        整合多种加密解密方式的函数
        :param text: 要加密或解密的文本内容
        :param mode: 加密解密模式，可选值为 "aes_encrypt"（AES加密）、"aes_decrypt"（AES解密）、
                    "rsa_encrypt"（RSA加密）、"rsa_decrypt"（RSA解密）、"sha256"（SHA256哈希）、
                    "md5"（MD5哈希）、"columnar_encrypt"（列换位加密）、"columnar_decrypt"（列换位解密）、
                    "caesar_encrypt"（凯撒加密）、"caesar_decrypt"（凯撒解密）
        :param key: 加密解密使用的密钥，对于对称加密、非对称加密等需要密钥的方式需传入，格式根据具体算法要求
        :param shift: 凯撒密码使用的偏移量，仅在凯撒加密或解密时使用
        :return: 根据选择的模式返回加密后的结果或者解密后的结果，如果是哈希则返回哈希值（对于哈希解密返回提示信息）
        """
        valid_modes = ["aes_encrypt", "aes_decrypt", "rsa_encrypt", "rsa_decrypt", "sha256",
                    "md5", "columnar_encrypt", "columnar_decrypt", "caesar_encrypt", "caesar_decrypt"]
        if mode not in valid_modes:
            return {"success": False, "error": "不支持的加密解密模式，请输入合法的式"}
        if mode in ["aes_encrypt", "aes_decrypt"]:
            if key is None:
                return {"success": False, "error": "AES加密或解密模式需要输入密钥"}
            if len(key) % 16!= 0:
                return {"success": False, "error": "AES密钥长度需为16的倍数"}
        if mode in ["rsa_encrypt", "rsa_decrypt"]:
            if key is None:
                return {"success": False, "error": "RSA加密或解密模式需要输入密钥"}
        if mode in ["caesar_encrypt", "caesar_decrypt"]:
            if shift is None:
                return {"success": False, "error": "凯撒加密或解密模式需要输入偏移量"}
        try:
            if mode == "aes_encrypt":
                print("正在执行AES加密操作...")
                def pad(s):
                    return s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
                key = key.encode('utf-8')
                text = pad(text).encode('utf-8')
                cipher = AES.new(key, AES.MODE_ECB)
                encrypted_text = cipher.encrypt(text)
                return {"success": True, "result": base64.b64encode(encrypted_text).decode('utf-8')}
            elif mode == "aes_decrypt":
                print("正在执行AES解密操作...")
                def unpad(s):
                    return s[:-ord(s[len(s) - 1:])]
                key = key.encode('utf-8')
                text = base64.b64decode(text)
                cipher = AES.new(key, AES.MODE_ECB)
                decrypted_text = cipher.decrypt(text)
                return {"success": True, "result": unpad(decrypted_text).decode('utf-8')}
            elif mode == "rsa_encrypt":
                print("正在执行RSA加密操作...")
                public_key = RSA.import_key(key)
                cipher = PKCS1_v1_5.new(public_key)
                encrypted_text = cipher.encrypt(text.encode('utf-8'))
                return {"success": True, "result": base64.b64encode(encrypted_text).decode('utf-8')}
            elif mode == "rsa_decrypt":
                print("正在执行RSA解密操作...")
                private_key = RSA.import_key(key)
                cipher = PKCS1_v1_5.new(private_key)
                decrypted_text = cipher.decrypt(base64.b64decode(text), None)
                return {"success": True, "result": decrypted_text.decode('utf-8')}
            elif mode == "sha256":
                if is_encrypt_mode(mode):
                    print("正在执行SHA256哈希计算操作...")
                    hash_object = hashlib.sha256(text.encode('utf-8'))
                    return {"success": True, "result": hash_object.hexdigest()}
                return {"success": False, "error": "SHA256是哈希算法，无法进行解密操作，原输入文本为: " + text}
            elif mode == "md5":
                if is_encrypt_mode(mode):
                    print("正在执行MD5哈希计算操作...")
                    hash_object = hashlib.md5(text.encode('utf-8'))
                    return {"success": True, "result": hash_object.hexdigest()}
                return {"success": False, "error": "MD5是哈希算法，无法进行解密操作，原输入文本为: " + text}
            elif mode == "columnar_encrypt":
                print("正在执行列换位加密操作...")
                key_order = sorted(range(len(key)), key=lambda k: key[k])
                num_columns = len(key)
                num_rows = len(text) // num_columns + (1 if len(text) % num_columns else 0)
                matrix = [['' for _ in range(num_columns)] for _ in range(num_rows)]
                index = 0
                for r in range(num_rows):
                    for c in range(num_columns):
                        if index < len(text):
                            matrix[r][c] = text[index]
                            index += 1
                ciphertext = ""
                for col in key_order:
                    for row in matrix:
                        ciphertext += row[col]
                return {"success": True, "result": ciphertext}
            elif mode == "columnar_decrypt":
                print("正在执行列换位解密操作...")
                key_order = sorted(range(len(key)), key=lambda k: key[k])
                num_columns = len(key)
                num_rows = len(text) // num_columns
                matrix = [['' for _ in range(num_columns)] for _ in range(num_rows)]
                index = 0
                for col in key_order:
                    for row in range(num_rows):
                        matrix[row][col] = text[index]
                        index += 1
                plaintext = ""
                for r in range(num_rows):
                    for c in range(num_columns):
                        plaintext += matrix[r][c]
                return {"success": True, "result": plaintext}
            elif mode == "caesar_encrypt":
                print("正在执行凯撒加密操作...")
                encrypted_text = ""
                for char in text:
                    if char.isalpha():
                        if char.isupper():
                            encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
                        else:
                            encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
                    else:
                        encrypted_text += char
                return {"success": True, "result": encrypted_text}
            elif mode == "caesar_decrypt":
                print("正在执行凯撒解密操作...")
                return encrypt_decrypt(text, "caesar_encrypt", shift=-shift)
            else:
                raise ValueError("不支持的加密解密模式")
        except ValueError as e:
            return {"success": False, "error": f"{mode} 操作过程中出现值错误: {str(e)}"}
        except TypeError as e:
            return {"success": False, "error": f"{mode} 操作过程中出现类型错误: {str(e)}"}
        except Exception as e:
            return {"success": False, "error": f"{mode} 操作过程中出现未知错误: {str(e)}"}
    def is_chinese_char(char):
        """
        判断字符是否为汉字。
        
        :param char: 要判断的字符
        :return: 如果是汉字则返回 True，否则返回 False
        """
        return True
    def parse_unicode(input_value):
        """
        解析 Unicode 编码字符串（格式为 U+XXXX 或 U+XXXXX）。
        
        :param input_value: Unicode 编码字符串
        :return: 对应的整数编码
        """
        if isinstance(input_value, str) and input_value.startswith('U+') and (len(input_value) == 6 or len(input_value) == 7):
            try:
                return int(input_value[2:], 16)
            except ValueError:
                raise ValueError("无效的 Unicode 编码格式")
        else:
            raise ValueError("输入必须是格式为 U+XXXX 或 U+XXXXX 的 Unicode 编码字")
    def utf8_code(input_value=None, mode=str):
        """
        查询字符的 Unicode 编码或 UTF-8 编码，或打印所有汉字及其编码。
        
        :param input_value: 要查询的字符或 Unicode 编码（字符串格式为 U+XXXX），如果为 None，则打印所有汉字及其编码
        :param mode: 查询模式，'unicode' 返回 Unicode 编码，'utf8' 返回 UTF-8 编码，'all' 打印所有汉字及其编码
        :return: 对应编码的值或 None
        """
        if mode not in ['unicode', 'utf8', 'all']:
            raise ValueError("模式参数必须是 'unicode'、'utf8' 或 'all'")
        
        if input_value is None:
            if mode == 'all':
                print("所有汉字及其编码:")
                for code_point in range(0x4E00, 0x3347B + 1):
                    try:
                        char = chr(code_point)
                        if is_chinese_char(char):
                            utf8_bytes = char.encode('utf-8')
                            print(f"字符: {char}, Unicode 编码: U+{code_point:04X}, UTF-8 编码: {utf8_bytes}")
                    except ValueError:
                        continue
            else:
                raise ValueError("当 input_value 为 None 时，mode 必须是 'all'")
        else:
            if mode == 'unicode':
                if isinstance(input_value, str) and len(input_value) == 1:
                    return ord(input_value)
                else:
                    raise ValueError("输入必须是单个字符")
            elif mode == 'utf8':
                if isinstance(input_value, str):
                    input_value = parse_unicode(input_value)
                if isinstance(input_value, int):
                    try:
                        return chr(input_value).encode('utf-8')
                    except ValueError:
                        raise ValueError("输入的 Unicode 编码无效")
                else:
                    raise ValueError("输入必须是 Unicode 编码整数或格式为 U+XXXX 的字符串")
    def create_vhdx_file(vhdx_path, size_in_gb):
        cmd = f'diskpart /s create_vhdx.txt'
        with open('create_vhdx.txt', 'w') as file:
            file.write(f'create vdisk file="{vhdx_path}" maximum={size_in_gb} type=expandable\n')
            file.write('exit\n')
        result = subprocess.run(cmd, shell=True, check=True)
        if result.returncode != 0:
            raise Exception(f"创建虚拟磁盘文件失败: {result.stderr}")
    def format_disk(disk_number, filesystem):
        cmd = f'diskpart /s format_{filesystem}.txt'
        with open(f'format_{filesystem}.txt', 'w') as file:
            file.write(f'select disk {disk_number}\n')
            file.write('clean\n')
            file.write('convert mbr\n')
            file.write('create partition primary\n')
            file.write('select partition 1\n')
            file.write('active\n')
            if filesystem.lower() == "ntfs":
                file.write('format fs=ntfs quick\n')
            elif filesystem.lower() == "fat32":
                file.write('format fs=fat32 quick\n')
            elif filesystem.lower() == "exfat":
                file.write('format fs=exfat quick\n')
            else:
                raise ValueError("不支持的文件系统")
            file.write('assign letter=v\n')
            file.write('exit\n')
        result = subprocess.run(cmd, shell=True, check=True)
        if result.returncode != 0:
            raise Exception(f"格式化磁盘失败: {result.stderr}")
    def vhdx(filesystem=str, path=str, CAPACITY=int):
        if filesystem is None or CAPACITY is None:
            raise ValueError("filesystem和CAPACITY参数不能为空")
        if not os.path.isabs(path):
            raise ValueError("path参数必须是绝对路径")
        supported_filesystems = ["ntfs", "fat32", "exfat"]
        if filesystem.lower() not in supported_filesystems:
            raise ValueError("不支持的文件系统")
        vhdx_path = path
        size_in_gb = CAPACITY
        create_vhdx_file(vhdx_path, size_in_gb)
        cmd = 'diskpart /s list_vdisks.txt'
        with open('list_vdisks.txt', 'w') as file:
            file.write('list vdisk\n')
            file.write('exit\n')
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        disk_number = None
        for line in result.stdout.split('\n'):
            if vhdx_path in line:
                disk_number = line.split()[0]
                break
        if disk_number is None:
            raise Exception("未找到虚拟磁盘")
        format_disk(disk_number, filesystem)
        print(f"虚拟磁盘已创建并格式化为{filesystem.upper()}: {vhdx_path}")
    
    def check_internet_connection():
        try:
            requests.get("http://www.baidu.com", timeout=3)
            return True
        except requests.ConnectionError:
            return False
    def show_error_popup(message):
        root = tk.Tk()
        root.withdraw()
        messagebox.showerror("错误", message)
        root.destroy()
    def get_file_size(url):
        try:
            with requests.head(url) as r:
                r.raise_for_status()
                return int(r.headers.get('content-length', 0))
        except requests.exceptions.RequestException as e:
            print(f"无法获取文件大小：{e}")
            pause()
            cls()
            return None
    def download_file(url, dest_folder):
        file_size = get_file_size(url)
        if file_size is None:
            print("无法获取文件大小，下载取消。")
            pause()
            cls()
            return None
        if not os.path.exists(dest_folder):
            os.makedirs(dest_folder)
        local_filename = os.path.join(dest_folder, url.split('/')[-1])
        try:
            with requests.get(url, stream=True) as r:
                r.raise_for_status()
                block_size = 8192
                t = tqdm(total=file_size, unit='iB', unit_scale=True, unit_divisor=1024, desc=local_filename)
                with open(local_filename, 'wb') as f:
                    for data in r.iter_content(block_size):
                        if download_stop_event.is_set():
                            print("下载已取消")
                            pause()
                            cls()
                            return None
                        t.update(len(data))
                        f.write(data)
                t.close()
            return local_filename
        except requests.exceptions.RequestException as e:
            print(f"请求错误：{e}")
            pause()
            cls()
            return None
    def search_and_download(software_name):
        software_name_lower = software_name.lower()
        found_software = [name for name in software_list if software_name_lower in name.lower()]
        if found_software:
            print(f"找到以下包含 '{software_name}' 的软件：")
            for i, software in enumerate(found_software, start=1):
                print(f"{i}. {software}")
            try:
                choices = input("请输入要下载的软件序号（多个序号用空格分隔，输入0取消下载）：")
                if '0' in choices:
                    print("取消下载。")
                    pause()
                    cls()
                    return
                
                selected_indices = [int(index) for index in choices.split() if 1 <= int(index) <= len(found_software)]
                selected_software = [found_software[index - 1] for index in selected_indices]
                
                if selected_software:
                    with ThreadPoolExecutor(max_workers=len(selected_software)) as executor:
                        futures = [executor.submit(download_file, software_list[software], "software") for software in selected_software]
                        for future in as_completed(futures):
                            try:
                                downloaded_file = future.result()
                                if downloaded_file:
                                    print(f"{software} 下载完成，保存路径：{downloaded_file}")
                                    log_download_history(software, downloaded_file)
                                    pause()
                                    cls()
                            except Exception as e:
                                print(f"下载时发生错误：{e}")
                                pause()
                                cls()
                else:
                    print("无效的序号。")
                    pause()
                    cls()
            except ValueError:
                print("请输入有效的序号。")
                pause()
                cls()
        else:
            print(f"没有找到包含 '{software_name}' 的软件。")
            pause()
            search_baidu(software_name)
    def search_baidu(software_name):
        search_url = f"https://www.baidu.com/s?wd={software_name}"
        webbrowser.open(search_url)
    def log_download_history(software_name, file_path):
        with open(download_history_file, 'a', encoding='utf-8') as f:
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            f.write(f"{timestamp} - {software_name} - {file_path}\n")
    def listen_for_escape():
        keyboard.wait('esc')
        download_stop_event.set()
    def main_control_loop(user_input):
        
        if user_input.lower() == 'exit':
            return
        else:
            search_and_download(user_input)
    def set_password():
        global PASSWORD1
        password_entry.delete(0, END)
        password_entry.config(state=tk.NORMAL)
        password_entry.focus_set()

    def save_password():
        global PASSWORD
        new_password = password_entry.get()
        if new_password:
            PASSWORD = new_password
            password_entry.config(state=tk.DISABLED)
        else:
            messagebox.showerror("错误", "密码不能为空")

    def refresh_process_list():
        process_list.delete(0, END)
        processes = [(proc.info['name'], proc.info['pid']) for proc in psutil.process_iter(['pid', 'name'])]
        processes.sort(key=lambda x: x[0])  # 按进程名称排序
        for name, pid in processes:
            process_list.insert(END, f"{name} (PID: {pid})")

    def select_process(event):
        selected = process_list.curselection()
        if selected:
            process_name = process_list.get(selected[0]).split(' (')[0]
            program_entry.delete(0, END)
            program_entry.insert(0, process_name)

    def start_monitoring():
        global TARGET_PROGRAM, IS_RUNNING, CMD_ALLOWED
        TARGET_PROGRAM = program_entry.get()
        if not TARGET_PROGRAM:
            messagebox.showerror("错误", "请输入目标程序名称")
            return
        
        if TARGET_PROGRAM.lower() == "cmd.exe":
            if messagebox.askokcancel("警告", "监控程序为cmd时可能会导致WinQuickTools无法运行和本程序的命令功能将被禁用，且可能会导致其他应用运行不正常。您确定要继续吗？"):
                CMD_ALLOWED = False
            else:
                return
        
        IS_RUNNING = True
        start_button.config(state=tk.DISABLED)
        stop_button.config(state=tk.NORMAL)
        set_password_button.config(state=tk.DISABLED)
        password_entry.config(state=tk.DISABLED)
        cmd_entry.config(state=tk.NORMAL if CMD_ALLOWED else tk.DISABLED)
        
        output_text.insert(tk.END, f"开始监控: {TARGET_PROGRAM} {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
        output_text.see(tk.END)
        
        def monitor():
            global PASSWORD_VERIFIED
            PASSWORD_VERIFIED = False
            while IS_RUNNING:
                for proc in psutil.process_iter(['pid', 'name']):
                    if proc.info['name'] == TARGET_PROGRAM:
                        if not PASSWORD_VERIFIED:
                            root.after(0, terminate_and_prompt, proc.info['pid'])
                        else:
                            root.after(0, start_program, proc.info['pid'])
                        break
                else:
                    if PASSWORD_VERIFIED:
                        root.after(0, start_program, None)
                    break
                time.sleep(0.1)
        
        threading.Thread(target=monitor, daemon=True).start()

    def stop_monitoring():
        global IS_RUNNING
        IS_RUNNING = False
        start_button.config(state=tk.NORMAL)
        stop_button.config(state=tk.DISABLED)
        set_password_button.config(state=tk.NORMAL)
        password_entry.config(state=tk.NORMAL)
        cmd_entry.config(state=tk.NORMAL)

    def terminate_and_prompt(pid):
        psutil.Process(pid).terminate()
        show_password_prompt()

    def show_password_prompt():
        password_prompt = tk.Toplevel(root)
        password_prompt.title("输入密码")
        
        tk.Label(password_prompt, text="请输入密码以继续:").pack(pady=10)
        
        password_entry_prompt = tk.Entry(password_prompt, show='*')
        password_entry_prompt.pack(pady=5)
        
        def on_submit():
            if password_entry_prompt.get() == PASSWORD:
                password_prompt.destroy()
                global PASSWORD_VERIFIED
                PASSWORD_VERIFIED = True
            else:
                messagebox.showerror("错误", "密码不正确")
        
        tk.Button(password_prompt, text="提交", command=on_submit).pack(pady=10)
        
        password_prompt.grab_set()
        root.wait_window(password_prompt)

    def start_program(pid):
        psutil.Process(pid).resume()

    def execute_cmd():
        cmd = cmd_entry.get()
        selected_disk = disk_var.get()
        if cmd.lower() == "start":
            start_monitoring()
        elif cmd.lower() == "close":
            stop_monitoring()
        else:
            if TARGET_PROGRAM.lower() == "cmd.exe":
                messagebox.showerror("错误", "监控程序为cmd时不能执行其他命令")
                return
            # 在所选磁盘上执行命令
            output = subprocess.getoutput(f'cd {selected_disk} && {cmd}')
            output_text.insert(tk.END, f"$ {cmd}\n{output}\n")
            output_text.see(tk.END)

    def display_system_info():
        info = f"""
    操作系统: {platform.system()} {platform.release()} {platform.version()}
    机器类型: {platform.machine()}
    处理器类型: {platform.processor()}
    网络名称: {platform.node()}
        """
        output_text.insert(tk.END, info)
        output_text.see(tk.END)
    root = tk.Tk()
    root.title("程序监控")
    root.geometry("1200x400")
    left_frame = tk.Frame(root)
    left_frame.pack(side=tk.LEFT, fill=tk.Y)
    tk.Label(left_frame, text="进程列表:").pack(pady=5)
    process_frame = tk.Frame(left_frame)
    process_frame.pack(pady=5, fill=tk.BOTH, expand=True)
    process_list = Listbox(process_frame, width=50)  # 增加进程列表的列宽
    process_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    scrollbar = Scrollbar(process_frame, orient="vertical")
    scrollbar.config(command=process_list.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    process_list.config(yscrollcommand=scrollbar.set)
    process_list.bind('<<ListboxSelect>>', select_process)
    refresh_button = tk.Button(left_frame, text="刷新进程列表", command=refresh_process_list)
    refresh_button.pack(pady=10)
    tk.Label(left_frame, text="目标程序:").pack(pady=5)
    program_entry = tk.Entry(left_frame)
    program_entry.pack(pady=5)
    tk.Label(left_frame, text="设置密码:").pack(pady=5)
    password_entry = tk.Entry(left_frame, show='*', state=tk.NORMAL)  # 默认解锁设定密码输入框
    password_entry.pack(pady=5)
    set_password_button = tk.Button(left_frame, text="设定密码", command=save_password)
    set_password_button.pack(pady=10)
    start_button = tk.Button(left_frame, text="开始监控", command=start_monitoring)
    start_button.pack(pady=10)
    stop_button = tk.Button(left_frame, text="停止监控", command=stop_monitoring)
    stop_button.pack(pady=10)
    stop_button.config(state=tk.DISABLED)
    right_frame = tk.Frame(root)
    right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
    tk.Label(right_frame, text="输出:").pack(pady=5)
    output_frame = tk.Frame(right_frame)
    output_frame.pack(pady=5, fill=tk.BOTH, expand=True)
    output_text = Text(output_frame, bg='black', fg='white')
    output_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    output_scrollbar = Scrollbar(output_frame, orient="vertical")
    output_scrollbar.config(command=output_text.yview)
    output_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    output_text.config(yscrollcommand=output_scrollbar.set)
    tk.Label(right_frame, text="选择磁盘:").pack(pady=5)
    disk_var = tk.StringVar()
    disk_combobox = ttk.Combobox(right_frame, textvariable=disk_var, values=[])
    disk_combobox.pack(pady=5)
    disk_combobox.set("C:\\")
    tk.Label(right_frame, text="命令:").pack(pady=5)
    cmd_entry = tk.Entry(right_frame, width=50) 
    cmd_entry.pack(pady=5)
    cmd_button = tk.Button(right_frame, text="执行", command=execute_cmd)
    cmd_button.pack(pady=10)
    def jiankong():
        display_system_info()
        refresh_process_list()
        root.mainloop() 
        search_and_download(user_input)
        download_stop_event.clear()
    print("测试完成。")
    os.system('cls')
    print('\033[1;34m beta\033[0m')
    print('加载界面......')
    for i in range(total_iterations + 1):
        print_progress_bar(i, total_iterations, prefix, suffix, length=length)
        time.sleep(0.03)
    print('完成')
    time.sleep(0.5)
    print('加载模块......')
    for i in range(total_iterations + 1):
        print_progress_bar(i, total_iterations, prefix, suffix, length=length)
        time.sleep(0.03)
    print('完成')
    time.sleep(0.5)
    print('加载信息......')
    for i in range(total_iterations + 1):
        print_progress_bar(i, total_iterations, prefix, suffix, length=length)
        time.sleep(0.05)
    print('完成')
    print('Qing Dynasty Co. , Ltd. 2023-2024')
    os.system('cls')
    print('__        ___              ___        _      _       _____           _')
    print('\ \      / (_)_ __        / _ \ _   _(_) ___| | __  |_   _|__   ___ | |___')
    print(' \ \ /\ / /| |  _ \ _____| | | | | | | |/ __| |/ /____| |/ _ \ / _ \| / __|')
    print('  \ V  V / | | | | |_____| |_| | |_| | | (__|   <_____| | (_) | (_) | \__ \\')
    print('   \_/\_/  |_|_| |_|      \__\_\__, _|_|\___|_|\_\    |_|\___/ \___/|_|___/')
    print('欢迎,' + '\033[1;34m' + beta_name_1 + '！\033[0m')
    time.sleep(5)
    os.system('cls')
    print('\033[1;38;46m# WinQuickTools 用户协议\033[0m')
    print('''
    ## 1. 定义
    本协议中的“软件”是指“WinQuickTools”命令行工具，包括其所有版本和更新。
    ## 2. 接受协议
    通过下载、安装或使用本软件，您确认您已阅读、理解并同意本协议的所有条款和条件。如果您不同意本协议的任何部分，您不得下载、安装或使用本软件。
    ## 3. 许可
    本软件根据 MIT 许可证授权。您可以在遵守本协议的前提下自由使用、复制、修改、合并、发布、分发、再许可和/或销售本软件的副本，并允许向其提供本软件的人这样做，但须符合以下条件：
    - 上面的版权声明和本许可声明应包含在本软件的所有副本或主要部分中。
    本软件按“原样”提供，不提供任何形式的明示或暗示保证，包括但不限于对适销性、适用于特定目的和非侵权的保证。在任何情况下，作者或版权持有人均不应对任何索赔、损害或其他责任承担责任，无论是在合同诉讼、侵权行为或其他方面，由于与本软件或本软件的使用或其他交易有关而引起的或与之相关的。
    ## 4. 使用限制
    - 您不得以任何形式对本软件进行二次分发、传播或销售。
    - 您在使用本软件时需遵守法律法规，不得利用本软件进行违法行为。
    - 您需自行承担使用本软件涉及到的第三方软件和服务的风险。
    ## 5. 免责声明
    - 用户使用本程序造成的任何损失和后果由用户自行承担，开发者不承担任何责任。
    - 本程序仅供个人学习和研究使用，禁止用于非法用途。
    - 用户需自行承担使用本程序涉及到的第三方软件和服务的风险。
    ## 6. 用户条款
    - 用户不得以任何形式对本程序进行二次分发、传播或销售。
    - 用户在使用本程序时需遵守法律法规，不得利用本程序进行违法行为。
    - 本程序为开源软件，用户可在遵守开源协议的前提下自由使用、修改和分发。
    - 用户在对程序进行任何修改后需保留原作者的署名和版权信息。
    - 如用户需将修改后的程序用于商业用途，需与原作者协商授权事宜。
    ## 7. 终止
    开发者有权在任何时候终止本协议，且无需提前通知。在此情况下，您必须立即停止使用本软件，并删除所有相关副本。
    ## 8. 修改
    开发者保留随时修改本协议的权利。任何修改将在发布后立即生效。您应定期检查本协议的更新。
    ## 9. 适用法律
    本协议受中华人民共和国法律管辖，任何争议应提交至开发者所在地的法院解决。
    ## 10. 联系方式
    如有任何问题或疑问，请通过以下方式联系开发者：
    - 邮箱：WinQuickTools@163.com
    - 网站：
    通过使用本软件，您确认您已阅读、理解并同意本协议的所有条款和条件。如果您不同意本协议的任何部分，您不得下载、安装或使用本软件。
    ''')
    ygn = input('是否同意以上条款？(y/n): ')
    if ygn == 'y' or ygn == 'Y':
        while True:
                os.system('cls')
                print('\033[1;34m beta\033[0m')
                try:
                    try:
                        print('\033[4;31m' + yiyan_new() + '\033[0m')
                        print('\033[4;31m'+ gushi() +'\033[0m')
                    except Exception as e:
                        Warning('加载失败' + e)
                except Exception as e:
                    Warning('模块错误')
                print('+++++++++++++++++++++++++++++++++++++++++++++')
                info = ''
                print('\033[1;34m邮箱：lxr090214@163.com\033[0m')
                print('[1]----->打开文件')
                print('[2]----->结束进程')
                print('[3]----->格式化磁盘')
                print('[4]----->打开网页')
                print('[5]----->重启')
                print('[6]----->重启并进入固件')
                print('[7]----->时间')
                print('[8]----->启动系统文件修复程序')
                print('[9]----->Hosts文件编辑器')
                print('[10]----->安装Windows(测试版)')
                print('[11]----->逻辑门')
                print('[12]----->计算器')
                print('[13]----->计算机信息')
                print('[14]----->关闭Windows更新')
                print('[15]----->生成密码')
                print('[16]----->搜索文件')
                print('[17]----->对比文件')
                print('[18]----->合并文件')
                print('[19]----->卸载软件')
                print('[20]----->编写代码')
                print('[21]----->AI')
                print('[22]----->进入OOBE')
                print('[23]----->查看文字编码')
                print('[24]----->命令提示符')
                print('[25]----->PowerShell')
                print('[26]----->注册表编辑器')
                print('[27]----->网络工具')
                print('[28]----->电脑硬件信息')
                print('[29]----->中央处理器信息')
                print('[30]----->扫描磁盘坏道')
                print('[31]----->Windows11优化#')
                print('[32]----->Windows11激活#')
                print('[33]----->系统镜像下载')
                print('[34]----->软件下载')
                print('[35]----->清理系统垃圾')
                print('[36]----->字符画生成')
                print('[37]----->字符加密与解密')
                print('[38]----->文本编辑器')
                print('[39]----->限制/监控程序运行(过年防小孩专用)')
                print('exit----->退出')
                c = input()
                if c == '[1]':
                    cls()
                    print('\033[1;34m beta\033[0m')
                    print('输入文件地址')
                    f = input()
                    print('输入文件名')
                    f4 = input()
                    os.system(f + f4)
                    cls()
                    continue
                elif c == '[2]':
                    cls()
                    print('\033[1;34m beta\033[0m')
                    list_processes()
                    pid_to_kill = int(input("请输入要结束的进程ID："))
                    kill_process(pid_to_kill)
                    continue
                elif c == '[3]':
                    cls()
                    print('\033[1;34m beta\033[0m')
                    print('\033[1;33m 警告：格式化硬盘后数据不可恢复！\033[0m')
                    cls()
                    print('指定要格式化硬盘的驱动器号')
                    d = input()
                    print('输入文件系统类型')
                    f2 = input()
                    if f2 == 'NTFS':
                        NTFS(d)
                        print('格式化成功')
                        continue
                    elif f2 == 'FAT32':
                        FAT32(d)
                        print('格式化成功')
                        continue
                    elif f2 == 'exFAT':
                        exFAT(d)
                        print('格式化成功')
                        continue
                    else:
                        error_unknown()
                        pause()
                        cls()
                        continue
                elif c == '[4]':
                    cls()
                    print('\033[1;34m beta\033[0m')
                    print('快捷输入')
                    print('360----->360搜索')
                    print('bd----->百度搜索')
                    print('bing----->必应')
                    print('gg----->谷歌')
                    print('输入要打开的URL,或序号')
                    w = input()
                    if w == '360':
                        webbrowser.open('https://www.so.com/')
                        cls()
                        continue
                    elif w == 'bd':
                        webbrowser.open('https://www.baidu.com/')
                        cls()
                        continue
                    elif w == 'bing':
                        webbrowser.open('https://cn.bing.com/')
                        cls()
                        continue
                    elif w == 'gg':
                        webbrowser.open('https://www.google.com/')
                        cls()
                        continue
                    else:
                        webbrowser.open(w)
                    cls()
                    continue
                elif c == 'exit':
                    cls()
                    break
                elif c == '[6]':
                    os.system('shutdown /s /fw /t 0')
                elif c == '[5]':
                    os.system('shutdown /r /t 0')
                elif c == '[7]':
                    cls()
                    time.sleep(3)
                    for i in range(10):
                        print('\033[1;34m beta\033[0m')
                        x =time.strftime('%y-%m-%d %H:%M:%S',time.localtime())
                        print(x)
                        time.sleep(0.5)
                        cls()
                elif c == '[8]':
                    cls()
                    print('启动修复......')
                    time.sleep(3)
                    cls()
                    os.system('Dism /Online /Cleanup-Image /ScanHealth')
                    os.system('Dism /Online /Cleanup-Image /CheckHealth')
                    os.system('Dism /Online /Cleanup-Image /RestoreHealth')
                    os.system('bootrec.exe /fixmbr')
                    os.system('bootrec.exe /fixboot')
                    os.system('bootrec.exe /rebuildbcd')
                    continue
                elif c == '[9]':
                    cls()
                    print('')
                    print('')
                    print('')
                    messagebox.showinfo('提示' , '使用此功能需要安装“PowerToys”')
                    os.system('cd C:\Program Files\PowerToys\WinUI3Apps')
                    os.system('PowerToys.Hosts.exe')
                    continue
                elif c == '[10]':
                    cls()
                    print('加载安装程序......')
                    for i in range(total_iterations + 1):
                        print_progress_bar(i, total_iterations, prefix, suffix, length=length)
                        time.sleep(0.05)
                    cls()
                    while True:
                        print('请注意，安装Windows11需要满足以下要求')
                        print('\033[1;34m 硬件要求\033[0m')
                        print('处理器：1 千兆赫 (GHz) 或更快，在 兼容的 64 位处理器 或芯片上的系统上 (SoC)')
                        print('内存：4 GB (GB) 或更大')
                        print('存储：64 GB 或更大的可用磁盘空间')
                        print('图形卡：与 DirectX 12 或更高版本兼容，具有 WDDM 2.0 驱动程序')
                        print('系统固件：UEFI，支持安全启动')
                        print('TPM： 受信任的平台模块 (TPM) 版本 2.0')
                        print('显示：高清 (720p) 显示器，9 英寸或更大监视器，每个颜色通道 8 位')
                        print('Internet 连接：Internet 连接是执行更新以及下载和使用某些功能所必需的')
                        print('\033[1;34m OS要求\033[0m')
                        print('若要直接升级到Windows 11，符合条件的Windows 10设备必须满足以下两个条件：')
                        print(' 运行Windows 10版本 2004 或更高版本')
                        print(' 已安装 2021 年 9 月 14 日安全更新或更高版本')
                        print('\033[1;34m 特定于功能的要求\033[0m')
                        print('5G 支持：需要支持 5G 的调制解调器')
                        print('Auto HDR：需要 HDR 监视器')
                        print('BitLocker to Go：需要 U 盘。 此功能在 Windows Pro 及更高版本中可用')
                        print('客户端 Hyper-V：需要具有二级地址转换 (SLAT) 功能的处理器。 此功能在 Windows 专业版及更高版本中提供')
                        print('DirectStorage：需要 NVMe SSD 来存储和运行使用标准 NVM Express 控制器驱动程序的游戏，以及支持着色器模型 6.0 的 DirectX12 GPU')
                        print('DirectX 12 Ultimate：适用于支持的游戏和图形芯片')
                        print('状态：需要能够检测到与设备的距离或与设备交互的意向的传感器')
                        print('智能视频会议：需要摄像机、麦克风和扬声器 (音频输出)')
                        print('多个语音助理：需要麦克风和扬声器')
                        print('对齐：三列布局需要 1920 有效像素或宽度更大的屏幕')
                        print('静音和取消静音：从任务栏需要视频摄像头、麦克风和扬声器（音频输出）。 应用必须与功能兼容才能启用全局静音/取消静音')
                        print('空间声音：需要支持硬件和软件')
                        print('Microsoft Teams：需要视频摄像头、麦克风和扬声器（音频输出）')
                        print('触控：需要支持多点触控的屏幕或显示器')
                        print('双重身份验证：需要使用 PIN、生物识别（指纹读取器或红外相机），或具有 Wi-Fi 或 蓝牙功能的电话')
                        print('语音键入：需要具有麦克风的电脑')
                        print('在语音上唤醒：需要新式待机电源模型和麦克风')
                        print('WI-Fi 6E：需要新的 WLAN IHV 硬件和驱动程序以及支持 Wi-Fi 6E 的 AP/路由器')
                        print('Windows Hello：需要一台配置为近红外 (IR) 成像或指纹读取器进行生物识别身份验证的相机。 没有生物识别传感器的设备可以使用带有 PIN 的 Windows Hello 或可移植的 Microsoft 兼容安全密钥')
                        print('Windows 投影：需要支持 Windows 显示驱动程序模型 (WDDM) 2.0 的显示适配器以及支持 Wi-Fi Direct 的 Wi-Fi 适配器')
                        print('Xbox 应用：需要 Xbox Live 帐户，并非所有地区都可用。 转到 Xbox Live 国家和地区 页面，获取有关可用性的最新信息')
                        print('\033[1;34m 虚拟机支持\033[0m')
                        print('VM：2')
                        print('存储：64 GB 或更大的磁盘空间')
                        print('安全性：')
                        print('        Azure：启用 vTPM 的 受信任启动')
                        print('        Hyper-V： 已启用安全启动和 TPM')
                        print('          常规设置：支持安全启动，已启用虚拟 TPM')
                        print('内存：4 GB 或更大')
                        print('处理器：两个或多个虚拟处理器')
                        print('    VM 主机处理器还必须满足Windows 11处理器要求')
                        print('    配置所需 VM 设置的过程取决于 VM 主机类型。 例如，必须在 BIOS 中启用运行 Hyper-V、虚拟化 (VT-x、VT-d) 的 VM 主机。 虚拟 TPM 2.0 独立于 Hyper-V 主机 TPM 状态或版本，在来宾 VM 中进行模拟')
                        print('以上资料均在https://learn.microsoft.com/zh-cn/windows/whats-new/windows-11-requirements中摘取')
                        print('是请输入y，否输入n，输入n将自动安装Windows10，输入r退出(y,n,r)')
                        version = input()
                        os.system('cls')
                        if version == 'y':
                            print('为保证下载速度，软件将使用系统默认下载器')
                            print('下载时请将ISO镜像保存在C:\\')
                            old1 = 'zh-cn_windows_11_business_editions_version_23h2_updated_may_2024_x64_dvd_4d6dc175.iso'
                            new1 = 'C:\Win11.iso'
                            url2 = 'ed2k://|file|zh-cn_windows_11_business_editions_version_23h2_updated_may_2024_x64_dvd_4d6dc175.iso|7012139008|08A52E6F10AFF1B3DE400D02B529BD84|/'
                            webbrowser.open(url2)
                            print('下载完成并移动文件后按Enter继续......')
                            fedsf = input()
                            print('启动安装......')
                            os.system('cd C:\\')
                            os.rename(old, new)
                            os.system('Win11.iso')
                            print('请提供ISO镜像挂载的盘符，程序将启动安装')
                            isopath = input()
                            os.system('cd ' + isopath)
                            os.system('setup.exe')
                            print('请根据安装程序操作')
                            os.system('pause')
                            cls()
                            continue
                        elif version == 'n':
                            print('为保证下载速度，软件将使用系统默认下载器')
                            print('下载时请将ISO镜像保存在C:\\')
                            old = 'C:\zh-cn_windows_10_business_editions_version_22h2_updated_june_2024_x64_dvd_1139f6a3.iso'
                            new = 'C:\Win10.iso'
                            url2 = 'ed2k://|file|zh-cn_windows_10_business_editions_version_22h2_updated_june_2024_x64_dvd_1139f6a3.iso|6942404608|F40A743548110202B4766BAC230CD9CF|/'
                            webbrowser.open(url2)
                            os.system('pause')
                            print('启动安装......')
                            os.system('cd C:\\')
                            os.rename(old, new)
                            os.system('Win10.iso')
                            print('请提供ISO镜像挂载的盘符，程序将启动安装')
                            isopath = input()
                            os.system('cd ' + isopath)
                            os.system('setup.exe')
                            print('请根据安装程序操作')
                            pause()
                            cls()
                            continue
                        else:
                            cls()
                            continue
                elif c == '[11]':
                    while True:
                        cls()
                        print('输入你想要体验逻辑门的类型')
                        print('[1]----->与门')
                        print('[2]----->或门')
                        print('[3]----->非门')
                        print('[4]----->与非门')
                        print('[5]----->或非门')
                        print('[6]----->异或门')
                        print('[7]----->退出')
                        g = input()
                        if g == '[1]':
                            a3 = ''
                            cls()
                            print('输入第一个数')
                            a1 = input()
                            print('输入第二个数')
                            a2 = input()
                            if a1 == '1' and a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            else:
                                a3 = '0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                        elif g == '[2]':
                            cls()
                            a3 = ''
                            print('输入0或1')
                            a1 = input()
                            print('输入0或1')
                            a2 = input()
                            if a1 == '1' or a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            elif a1 == '1' and a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            else:
                                a3 = '0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue     
                        elif g == '[3]':
                            cls()
                            a3 = ''
                            print('输入0或1')
                            a1 = input()
                            if a1 == '1':
                                a3 = '0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            elif a1 == '0':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                        elif g == '[4]':
                            cls()
                            a3 = ''
                            print('输入0或1')
                            a1 = input()
                            print('输入0或1')
                            a2 = input()
                            if a1 == '0' and a2 == '0' or a1 == '1' and a2 == '0' or a1 == '0' and a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(4)
                                cls()
                                continue
                            elif a1 == '1' and a2 == '1':
                                a3 = '0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                        elif g == '[5]':
                            cls()
                            a3 = ''
                            print('输入0或1')
                            a1 = input()
                            print('输入0或1')
                            a2 = input()
                            if a1 == '1' or a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            else:
                                a3 = '0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                        elif g == '[6]':
                            cls()
                            a3 = ''
                            print('输入0或1')
                            a1 = input()
                            print('输入0或1')
                            a2 = input()
                            if a1 == '1' and a2 == '0' or a1 == '0' and a2 == '1':
                                a3 = '1'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            elif a1 == '1' and a2 == '1':
                                a3 ='0'
                                print(a3)
                                time.sleep(5)
                                cls()
                                continue
                            elif a1 == '0' and a2 == '0':
                                a3 = '0'
                                print(a3)
                                pause()
                                cls()
                                continue
                            else:
                                cls()
                                error_unknown()
                                continue
                        elif g == '[7]':
                            cls()
                            break
                        else:
                            error_unknown()
                            pause()
                            cls()
                            continue
                elif c == '[12]':
                    cls()
                    print('[1]----->加法')
                    print('[2]----->减法')
                    print('[3]----->乘法')
                    print('[4]----->除法')
                    print('[5]----->平方根')
                    print('[6]----->面积')
                    print('[7]----->体积')
                    print('exit----->Exit')
                    j = input()
                    if j == '[1]':
                        print('输入第一个数')
                        s = input()
                        print('输入第二个数')
                        s1 = input()
                        print('结果:')
                        s2 = add(s , s1)
                        pause()
                        cls()
                        continue
                    elif j == '[2]':
                        print('输入第一个数')
                        s = input()
                        print('输入第二个数')
                        s1 = input()
                        print('结果:')
                        s2 = subtract(s , s1)
                        pause()
                        cls()
                        continue
                    elif j == '[3]':
                        print('输入第一个数')
                        s = input()
                        print('输入第二个数')
                        s1 = input()
                        print('结果:')
                        s2 = multiply(s , s1)
                        pause()
                        cls()
                        continue
                    elif j == '[4]':
                        cls()
                        print('输入第一个数')
                        s = input()
                        print('输入第二个数')
                        s1 = input()
                        print('结果:')
                        s2 = divide(s , s1)
                        pause()
                        cls()
                        continue
                    elif j == '[5]':
                        cls()
                        print('输入一个数')
                        c = input()
                        ecxs = str(square_root(c))
                        print(f'{c}的平方根是{ecxs}')
                        pause()
                        cls()
                        continue
                    elif j == '[6]':
                        cls()
                        while True:
                            print('[1]----->长方形')
                            print('[2]----->正方形')
                            print('[3]----->梯形')
                            print('[4]----->三角形')
                            print('exit----->退出')
                    elif j == 'exit':
                        break
                    else:
                        error_unknown()
                        time.sleep(1)
                        cls()
                        continue
                elif c == '[13]':
                    cls()
                    while True:
                        print('[1]----->退出')
                        os.system('winver')
                        os.system('systeminfo')
                        q = input()
                        if q == '[1]':
                            cls()
                            break
                        else:
                            cls()
                            continue
                elif c == '[14]':
                    cls()
                    try:
                        print('程序将执行以下操作:')
                        print('    *关闭Windows更新服务')
                        print('    *禁用Windows更新服务自启动')
                        print('    *删除wuapi.dll')
                        print('    *删除wuauclt.exe')
                        print('    *删除wuauserv.exe')
                        update = input('是否继续? [Y/N]')
                        if update == 'y' or update == 'Y':
                            cls()
                            disable_windows_update()
                            continue
                        else:
                            cls()
                            continue
                    except:
                        print('发生错误')
                        time.sleep(5)
                        cls()
                        continue
                elif c == '[15]':
                    while True:
                        os.system('cls')
                        print('[1]----->数字')
                        print('[2]----->数字|小写字母')
                        print('[3]----->数字|小写字母|大写字母')
                        print('[4]----->数字|小写字母|大写字母|特殊字符')
                        print('[5]----->Exit')
                        bit = input()
                        if bit == '[1]':
                            os.system('cls')
                            print('请问您要生成多少位的密码?推荐12位')
                            password = input()
                            password12 = int(password)
                            gp = generate_password(password12)
                            print("生成的密码是：", gp)
                            os.system('pause')
                            os.system('cls')
                        elif bit == '[2]':
                            os.system('cls')
                            print('请问您要生成多少位的密码?推荐12位')
                            password = input()
                            password12 = int(password)
                            gp = generate_password_1_a(password12)
                            print("生成的密码是：", gp)
                            os.system('pause')
                            os.system('cls')
                        elif bit == '[3]':
                            os.system('cls')
                            print('请问您要生成多少位的密码?推荐12位')
                            password = input()
                            password12 = int(password)
                            gp = generate_password_1_a_A(password12)
                            print("生成的密码是：", gp)
                            os.system('pause')
                            os.system('cls')
                        elif bit == '[4]':
                            os.system('cls')
                            print('请问您要生成多少位的密码?推荐12位')
                            password = input()
                            password12 = int(password)
                            gp = generate_password_1_a_A_bit(password12)
                            print("生成的密码是：", gp)
                            os.system('pause')
                            os.system('cls')
                        elif bit == '[5]':
                            os.system('cls')
                            continue
                        else:
                            error_unknown()
                            pause()
                            cls()
                            continue
                elif c == '[16]':
                    cls()
                    directory = input("请输入要搜索的文件夹：")
                    filename = input("请输入要搜索的文件名：")
                    search_file(directory, filename)
                    time.sleep(5)
                    t = input()
                elif c == '[17]':
                    cls()
                    file1 = input("请输入第一个文件路径：")
                    file2 = input("请输入第二个文件路径：")
                    compare_files(file1, file2)
                    time.sleep(5)
                elif c == '[18]':
                    cls()
                    directory = input("请输入要搜索的文件夹：")
                    output_file = input("请输入输出文件的路径：")
                    merge_files(directory, output_file)
                    time.sleep(5)
                elif c == '[19]':
                    cls()
                    list_processes()
                    software_to_uninstall = input("请输入要卸载的软件名称：")
                    list_installed_software()
                    uninstall_software(software_to_uninstall)
                elif c == '[20]':
                    cls()
                elif c == '[21]':
                    cls()
                elif c == '[22]':
                    while True:
                        cls()
                        print('输入系统版本')
                        print('[1]----->Windows 10')
                        print('[2]----->Windows 11')
                        print('[3]----->Exit')
                        ef = input()
                        if ef == '[1]':
                            cls()
                            os.chdir(os.path.dirname(os.path.abspath(__file__)))
                            subprocess.run(["msoobe.exe"])
                            cls()
                            continue
                        elif ef == '[2]':
                            cls()
                            os.chdir(os.path.dirname(os.path.abspath(__file__)))
                            subprocess.run(["msoobe.exe"])
                            cls()
                            continue
                        elif ef == '[3]':
                            cls()
                            break
                        else:
                            cls()
                            error_unknown()
                            pause()
                            continue
                elif c == '[23]':
                    while True:
                        cls()
                        print('选择一种打开方式：')
                        print('[1]----->打印所有字符')
                        print('[2]----->根据UTF-8编码查找字符')
                        print('[3]----->根据字符查找UTF-8编码')
                        dfge = input('')
                        if dfge == '[]':
                            cls()
                            utf8_code(None, 'all')
                            pause()
                            cls()
                            continue
                        elif dfge == '[2]':
                            cls()
                            xdc = input('请输入要查找的字符')
                            try:
                                unicode_code = utf8_code(xdc, 'unicode')
                                print(f"字符 '{xdc}' 的 Unicode 编码是: U+{unicode_code:04X}")
                                pause()
                                cls()
                                continue
                            except ValueError as e:
                                print(f"无效的字符: {xdc}")
                                pause()
                                cls()
                                continue
                        elif dfge == '[3]':
                            cls()
                            unicode_str = input('请输入要查找的编码')
                            try:
                                xdc = utf8_code(unicode_str, 'utf8')
                                xd = xdc.decode('utf-8')
                                print(f"Unicode 编码 {unicode_str} 对应的字符在 UTF-8 编码中的字节表示是: {xd}")
                                pause()
                                cls()
                                continue
                            except ValueError as e:
                                print(f"无效的 Unicode 编码: {unicode_str}")
                                pause()
                                cls()
                                continue
                        elif dfge == 'exit':
                            cls()
                            break
                        else:
                            cls()
                            error_unknown()
                            pause()
                            cls()
                            continue
                elif c == '[24]':
                    os.system('cls')
                    print('选择一种打开方式：')
                    print('[1]----->内置(推荐,不依赖环境,可直接运行)')
                    print('[2]----->外置(不推荐,依赖环境,可能无法运行)')
                    fdgvfg = input()
                    if fdgvfg == '[1]':
                        while True:
                            print('Microsoft Windows [版本 10.0.27686.1000]')
                            print('版权所有 (c) Microsoft Corporation。保留所有权利。')
                            print('')
                            path = os.path.dirname(os.path.abspath(__file__))
                            path = path.capitalize()
                            command = input(path + '>')
                            if command == 'exit':
                                cls()
                                break
                            else:
                                os.system(command)
                elif c == '[25]':
                    cls()
                    print('选择一种打开方式：')
                    print('[1]----->内置(推荐,不依赖环境,可直接运行)')
                    print('[2]----->外置(不推荐,依赖环境,可能无法运行)')
                    fdgvfg = input()
                    if fdgvfg == '1':
                        cls()
                        print('Windows PowerShell')
                        print('版权所有 (c) Microsoft Corporation。保留所有权利。')
                        while True:
                            path = os.path.dirname(os.path.abspath(__file__))
                            path = path.capitalize()
                            command = input('PS ' + path + '>')
                            if command == 'exit':
                                cls()
                                break
                            else:
                                os.system('powershell' + command)
                    elif fdgvfg == '[2]':
                        cls()
                        os.system('start cmd')
                        continue
                elif c == '[26]':
                    cls()
                    os.system('regedit')
                    cls()
                    continue
                elif c == '[27]':
                    while True:
                        cls()
                        print('[1]----->移除Microsoft Defender')
                        print('[2]----->检测是否连接到网络')
                        print('[3]----->链接WiFi')
                        print('[4]----->网站压力测试')
                        print('[5]----->检测网络速度')
                        print('[6]----->查询域名是否被注册')
                        print('[7]-----查询域名信息')
                        print('[8]----->IP地址扫描')
                        print('[9]----->扫描端口')
                        print('[10]----->获取所有设备的MAC地址')
                        print('exit----->退出')
                        c = input()
                        if c == '[1]':
                            cls()
                            iodkm = messagebox.askquestion('警告', '移除Microsoft Defender可能会使你的电脑变得不安全，你确定要移除吗？')
                            if iodkm == 'yes':
                                cls()
                                remove_defender()
                                messagebox.showinfo('提示', '已移除Microsoft Defender')
                                re = messagebox.askquestion('提示', '是否重新启动电脑？')
                                if re == 'yes':
                                    cls()
                                    os.system('shutdown /r /t 0')
                                else:
                                    cls()
                                    continue
                            else:
                                messagebox.showinfo('提示', '已取消移除Microsoft Defender')
                                pause()
                                cls()
                                continue
                        elif c == '[2]':
                            cls()
                            if Internet():
                                messagebox.showinfo('提示', '已连接到网络')
                                cls()
                                continue
                            else:
                                messagebox.showinfo('提示', '未连接到网络')
                                cls()
                                continue
                        elif c == '[3]':
                            cls()
                            connect_to_wifi()
                            cls()
                            continue
                        elif c == '[4]':
                            cls()
                            print('请输入你要测试的网站:')
                            website = input()
                            print('请输入你要测试的并发数:')
                            concurrency = int(input())
                            print('请输入你要测试的时间(秒):')
                            duration = int(input())
                            test_website(website, concurrency, duration)
                            cls()
                            continue
                        elif c == '[5]':
                            cls()
                            test_network_speed()
                            pause()
                            cls()
                            continue
                        elif c == '[6]':
                            cls()
                            print('请输入你要查询的域名:')
                            domain = input()
                            query_domain(domain)
                            pause()
                            cls()
                            continue
                        elif c == '[7]':
                            cls()
                            print('请输入你要查询的域名:')
                            domain = input()
                            get_domain_info(domain)
                            pause()
                            cls()
                            continue
                        elif c == '[8]':
                            cls()
                            scan_range('192.168.0.0', '192.168.255.255')
                            pause()
                            cls()
                            continue
                        elif c == '[9]':
                            cls()
                            print('请输入你要扫描的起始端口号:')
                            start_port = int(input())
                            print('请输入你要扫描的结束端口号:')
                            end_port = int(input())
                            scan_ports('192.168.0.1', start_port, end_port)
                            pause()
                            cls()
                            continue
                        elif c == '[10]':
                            cls()
                            print('请输入你要扫描的IP地址:')
                            ip = input()
                            get_and_print_lan_mac_addresses()
                        elif c == 'exit':
                            cls()
                            break
                elif c == '[28]':
                    try:
                        display_all_hardware_info()
                    except Exception as e:
                        messagebox.showerror('Error Code:', str(e))
                        pause()
                        cls()
                        continue
                elif c == '[29]':
                    cls()
                    display_cpu_info()
                    pause()
                    cls()
                    continue
                elif c == '[30]':
                    cls()
                    scan_bad_sectors_windows()
                    pause()
                    cls()
                    continue
                elif c == '[31]':
                    if is_windows_11_or_higher():
                        pass
                    else:
                        cls()
                        print('您的系统版本低于Windows 11，无法使用此功能')
                        pause()
                        cls()
                        continue
                    cls()
                    print('[1]----->恢复Windows10右键菜单栏')
                    print('[2]----->')
                    c = input()
                    if c == '[1]':
                        cls()
                        restore_right_click_menu()
                        pause()
                        cls()
                        continue
                elif c == '[32]':
                    cls()
                    print('输入你的系统版本')
                    print('[1]----->专业版')
                    print('[2]----->家庭版')
                    print('[3]----->专业工作站版')
                    print('[4]----->Windows Server')
                    print('exit----->退出')
                    c = input()
                    if c == '[1]':
                        cls()
                        Warning('请勿在中国大陆以外地区使用，否则后果自负！')
                        c = input('确定要执行吗？(Y/N)')
                        if c == 'Y' or c == 'y':
                            try:
                                cmd('slmgr -ipk W269N-WFGWX-YVC9B-4J6C9-T83GX')
                                cmd('slmgr -skms kms.0t.net.cn')
                                cmd('slmgr -ato')
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == 'N' or c == 'n':
                            cls()
                            continue
                    elif c == '[2]':
                        cls()
                        Warning('请勿在中国大陆以外地区使用，否则后果自负！')
                        c = input('确定要执行吗？(Y/N)')
                        if c == 'Y' or c == 'y':
                            try:
                                cmd('slmgr -ipk YTMG3-N6DKC-DKB77-7M9GH-8HVX7')
                                cmd('slmgr -skms kms.0t.net.cn')
                                cmd('slmgr -ato')
                                print('已激活Windows家庭版')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == 'N' or c == 'n':
                            cls()
                            continue
                    elif c == '[3]':
                        cls()
                        Warning('请勿在中国大陆以外地区使用，否则后果自负！')
                        c = input('确定要执行吗？(Y/N)')
                        if c == 'Y' or c == 'y':
                            try:
                                cmd('slmgr -ipk XCJDN-D6Y2W-7J79X-7P27B-DPGFK')
                                cmd('slmgr -skms kms.0t.net.cn')
                                cmd('slmgr -ato')
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == 'N' or c == 'n':
                            cls()
                            continue
                    elif c == '[4]':
                        cls()
                        print('输入系统版本')
                        print('[1]----->Windows Server 2025 Standard')
                        print('[2]----->Windows Server 2022 Standard')
                        print('[3]----->Windows Server 2019 Standard')
                        print('[4]----->Windows Server 2016 Standard')
                        print('[5]----->Windows Server 2012 R2 Standard')
                        print('[6]----->Windows Server 2012 Standard')
                        print('[7]----->Windows Server 2008 R2 Standard')
                        print('[8]----->Windows Server 2008 Standard')
                        print('[9]----->自定义')
                        print('exit----->退出')
                        c = input()
                        if c == '[1]':
                            cls()
                            try:
                                Activate_Windows('MFY9F-XBN2F-TYFMP-CCV49-RMYVH')
                                print('已激活Windows Server 2025 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[2]':
                            cls()
                            try:
                                Activate_Windows('VDYBN-27WPP-V4HQT-9VMD4-VMK7H')
                                print('已激活Windows Server 2022 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[3]':
                            cls()
                            try:
                                Activate_Windows('WMDGN-G9PQG-XVVXX-R3X43-63DFG')
                                print('已激活Windows Server 2019 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[4]':
                            cls()
                            try:
                                Activate_Windows('QXN3J-843V9-89VM3-KWXFJ-7FT3F')
                                print('已激活Windows Server 2016 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[5]':
                            cls()
                            try:
                                Activate_Windows('NB4WH-BBBYV-3MPPC-9RCMV-46XCB')
                                print('已激活Windows Server 2012 R2 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[6]':
                            cls()
                            try:
                                Activate_Windows('VDNYM-JBKJ7-DC4X9-BT3QR-JHRGY')
                                print('已激活Windows Server 2012 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[7]':
                            cls()
                            try:
                                Activate_Windows('YC6KT-GKW9T-YTKYR-T4X34-R7VHC')
                                print('已激活Windows Server 2008 R2 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[8]':
                            cls()
                            try:
                                Activate_Windows('P36VD-22V68-JVM2W-DBC77-MK98W')
                                print('已激活Windows Server 2008 Standard')
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        elif c == '[9]':
                            cls()
                            print('输入版本')
                            c = input()
                            print('输入密钥,格式应为XXXXX-XXXXX-XXXXX-XXXXX-XXXXX')
                            C1 = input()
                            try:
                                Activate_Windows(c, C1)
                                pause()
                                cls()
                                continue
                            except Exception as e:
                                Warning('Error code:{e}')
                                pause()
                                cls()
                                continue
                        
                        else:
                            cls()
                            continue
                elif c == '[26]':
                    cls()
                    os.system('regedit')
                    cls()
                    continue
                elif c == '[33]':
                    cls()
                    print('输入要下载系统的类型')
                    print('[1]----->Windows')
                    print('[2]----->Linux')
                    print('exit----->退出')
                    c = input()
                    if c == '[1]':
                        cls()
                        print('输入要下载Windows的类型')
                        print('[1]----->Windows')
                        print('[2]----->Windows Server')
                        print('exit----->退出')
                        c = input()
                        if c == '[1]':
                            while True:
                                cls()
                                print('输入要下载Windows的版本')
                                print('[1]----->Windows 10')
                                print('[2]----->Windows 11')
                                print('[3]----->Windows 7')
                                print('[4]----->Windows 8')
                                print('[5]----->Windows 8.1')
                                print('[6]----->Windows Vista')
                                print('[7]----->Windows XP')
                                print('[8]----->Windows 2000')
                                print('[9]----->Windows 98')
                                print('[10]----->Windows 95')
                                print('[11]----->Windows 3.2')
                                print('exit----->退出')
                                c = input()
                                if c == '[1]':
                                    cls()
                                    webbrowser.open('ed2k://|file|zh-cn_windows_10_business_editions_version_22h2_updated_nov_2024_x64_dvd_c850f3d7.iso|7008780288|B58761A02403D53C4029C50F46CF525D|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|zh-cn_windows_10_business_editions_version_22h2_updated_nov_2024_x64_dvd_c850f3d7.iso|7008780288|B58761A02403D53C4029C50F46CF525D|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[2]':
                                    cls()
                                    webbrowser.open('ed2k://|file|zh-cn_windows_11_business_editions_version_24h2_updated_nov_2024_x64_dvd_29061b8c.iso|6292852736|7B52B157D9D098D944A7B6F7E7E6E794|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|zh-cn_windows_11_business_editions_version_24h2_updated_nov_2024_x64_dvd_29061b8c.iso|6292852736|7B52B157D9D098D944A7B6F7E7E6E794|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[3]':
                                    cls()
                                    webbrowser.open('ed2k://|file|7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x64FRE_en-us.iso|5876357120|9C55A020B327AD60CB8A37D0317743F2|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x64FRE_en-us.iso|5876357120|9C55A020B327AD60CB8A37D0317743F2|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[4]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_8_pro_vl_x64_dvd_917773.iso|3558014976|7956620A80428F37D4F2989CB5CF3B5A|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_8_pro_vl_x64_dvd_917773.iso|3558014976|7956620A80428F37D4F2989CB5CF3B5A|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[5]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_8.1_enterprise_with_update_x64_dvd_6050374.iso|4317065216|AC8215A13817CC0EC4EA42E5C92E88B7|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_8.1_enterprise_with_update_x64_dvd_6050374.iso|4317065216|AC8215A13817CC0EC4EA42E5C92E88B7|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[6]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_vista_enterprise_with_sp2_x64_dvd_x15-40402.iso|3104415744|D0CF708192BF9596CC603DF53ABDB76D|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_vista_enterprise_with_sp2_x64_dvd_x15-40402.iso|3104415744|D0CF708192BF9596CC603DF53ABDB76D|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[7]':
                                    cls()
                                    webbrowser.open('ed2k://|file|zh-hans_windows_xp_professional_with_service_pack_3_x86_cd_vl_x14-74070.iso|630237184|EC51916C9D9B8B931195EE0D6EE9B40E|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|zh-hans_windows_xp_professional_with_service_pack_3_x86_cd_vl_x14-74070.iso|630237184|EC51916C9D9B8B931195EE0D6EE9B40E|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[8]':
                                    cls()
                                    webbrowser.open('ed2k://|file|ZRMPSEL_CN.iso|402690048|00D1BDA0F057EDB8DA0B29CF5E188788|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|ZRMPSEL_CN.iso|402690048|00D1BDA0F057EDB8DA0B29CF5E188788|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[9]':
                                    cls()
                                    webbrowser.open('https://dl-alt1.winworldpc.com/Abandonware%20Operating%20Systems/PC/Microsoft%20Windows/Windows%2098-ME/Microsoft%20Windows%2098%20Update%20(FE%20to%20SE).7z')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:https://dl-alt1.winworldpc.com/Abandonware%20Operating%20Systems/PC/Microsoft%20Windows/Windows%2098-ME/Microsoft%20Windows%2098%20Update%20(FE%20to%20SE).7z')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[10]':
                                    cls()
                                    webbrowser.open('https://dl.winworldpc.com/Microsoft%20Windows%2095B%20(4.00.1111)%20(OSR2)%20[English]%20(CD).7z')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:https://dl.winworldpc.com/Microsoft%20Windows%2095B%20(4.00.1111)%20(OSR2)%20[English]%20(CD).7z')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[11]':
                                    cls()
                                    webbrowser.open('http://static.hotsun168.com/20th/271/WIN32_ISO.rar')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:http://static.hotsun168.com/20th/271/WIN32_ISO.rar')
                                    pause()
                                    cls()
                                    continue
                                elif c == 'exit':
                                    break
                        elif c == '[2]':
                            while True:
                                cls()
                                print('[1]----->Windows Server 2025')
                                print('[2]----->Windows Server 2022')
                                print('[3]----->Windows Server 2019')
                                print('[4]----->Windows Server 2016')
                                print('[5]----->Windows Server 2012 R2')
                                print('[6]----->Windows Server 2012')
                                print('[7]----->Windows Server 2008 R2')
                                print('[8]----->Windows Server 2008')
                                c = input()
                                if c == '[1]':
                                    cls()
                                    webbrowser.open('ed2k://|file|zh-cn_windows_server_2025_updated_nov_2024_x64_dvd_ccbcec44.iso|7409489920|99613B37CAE109360D15F7EDC178175E|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|zh-cn_windows_server_2025_updated_nov_2024_x64_dvd_ccbcec44.iso|7409489920|99613B37CAE109360D15F7EDC178175E|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[2]':
                                    cls()
                                    webbrowser.open('ed2k://|file|zh-cn_windows_server_2022_updated_sep_2024_x64_dvd_cab4e960.iso|6155229184|3B389D2652259B8BA29E4736E701616A|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|zh-cn_windows_server_2022_updated_sep_2024_x64_dvd_cab4e960.iso|6155229184|3B389D2652259B8BA29E4736E701616A|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[3]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2019_updated_july_2020_x64_dvd_2c9b67da.iso|5675251712|19AE348F0D321785007D95B7D2FAF320|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2019_updated_july_2020_x64_dvd_2c9b67da.iso|5675251712|19AE348F0D321785007D95B7D2FAF320|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[4]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2016_vl_x64_dvd_11636695.iso|6302720000|44742A3D464B9765203E2A4DB73FF704|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2016_vl_x64_dvd_11636695.iso|6302720000|44742A3D464B9765203E2A4DB73FF704|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[5]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2012_r2_essentials_with_update_x64_dvd_6052796.iso|5201313792|C6E9486A9364E9A918830940EF5A1946|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2012_r2_essentials_with_update_x64_dvd_6052796.iso|5201313792|C6E9486A9364E9A918830940EF5A1946|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[6]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2012_x64_dvd_915588.iso|3826081792|6A56281311F9FE6973F66CF36E2F50BE|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2012_x64_dvd_915588.iso|3826081792|6A56281311F9FE6973F66CF36E2F50BE|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[7]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2008_r2_standard_enterprise_datacenter_web_x64_dvd_x15-50360.iso|3270336512|994401AF40CF454135F4F9510829405D|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2008_r2_standard_enterprise_datacenter_web_x64_dvd_x15-50360.iso|3270336512|994401AF40CF454135F4F9510829405D|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == '[8]':
                                    cls()
                                    webbrowser.open('ed2k://|file|cn_windows_server_2008_standard_enterprise_and_datacenter_with_sp2_x64_dvd_x15-41319.iso|2952992768|5F2CA73C9DA296CB05E7C0319F7D0E62|/')
                                    print('为保证下载速度，程序使用浏览器下载。推荐使用迅雷。')
                                    print('若无开始 请复制地址到浏览器:ed2k://|file|cn_windows_server_2008_standard_enterprise_and_datacenter_with_sp2_x64_dvd_x15-41319.iso|2952992768|5F2CA73C9DA296CB05E7C0319F7D0E62|/')
                                    pause()
                                    cls()
                                    continue
                                elif c == 'exit':
                                    cls()
                                    break
                elif c == '[34]':
                    while True:
                        cls()
                        keys_list = software_list.keys()
                        for i in keys_list:
                            print(i)
                        user_input = input("请输入要搜索的软件名称或关键字（输入'exit'退出程序）：")
                        main_control_loop(user_input)
                elif c == '[35]':
                    cls()
                    clean_and_list()
                    pause()
                    cls()
                    continue
                elif c == '[36]':
                    cls()
                    convert_image_to_ascii_art()
                    pause()
                    cls()
                    continue
                elif c == '[37]':
                    cls()
                    mode = input("请输入加密解密模式（可选值：aes_encrypt、aes_decrypt、rsa_encrypt、rsa_decrypt、sha256、md5、columnar_encrypt、columnar_decrypt、caesar_encrypt、caesar_decrypt）：")
                    if mode in ["aes_encrypt", "aes_decrypt", "rsa_encrypt", "rsa_decrypt"]:
                        key = input("请输入密钥：")
                    elif mode in ["caesar_encrypt", "caesar_decrypt"]:
                        shift = int(input("请输入偏移量（整数）："))
                    text = input("请输入要加密或解密的文本内容：")
                    try:
                        result = encrypt_decrypt(text, mode, key=key, shift=shift)
                        print("操作结果:", result)
                        pause()
                        cls()
                        continue
                    except ValueError as e:
                        Warning(f'错误：{e}')
                        pause()
                        cls()
                        continue 
                elif c == '[38]':
                    cls()
                    start_TextEditor()
                    cls()
                    continue
                elif c == '[39]':
                    cls()
                    jiankong()
                    cls()
                    continue
                elif c == 'qing':
                    os.system('cls')
                    messagebox.showinfo('???', '...')
                    print('???')
                    print('...')
                    time.sleep(3)
                    messagebox.showinfo('???', '......')
                    print('......')
                    time.sleep(3)
                    messagebox.showinfo('???', '............')
                    print('............')
                    time.sleep(3)
                    sdxd = random.randint(0, 1)
                    messagebox.showinfo('作者', '你发现了彩蛋！')
                    messagebox.showinfo('作者', '你觉得')
                    input_text = simpledialog.askstring('作者', '你觉得好用吗?')
                    if input_text == '好用' or input_text == '是':
                        messagebox.showinfo('WinQuickTools', '谢谢！')
                        messagebox.showinfo('WinQuickTools', '作者:pmx1119')
                        messagebox.showinfo('WinQuickTools', '作者QQ:3764588384')
                        messagebox.showinfo('WinQuickTools', '作者邮箱:WinQuickTools@163.com')
                        messagebox.showinfo('WinQuickTools', '作者WeChat:微创工作室')
                        messagebox.showinfo('WinQuickTools', '作者抖音:ggg')
                        messagebox.showinfo('WinQuickTools', '还有，本程序是个人编写的，精力有限，所以更新速度可能较慢，请谅解！')
                        messagebox.showinfo('WinQuickTools', '去爱发电支持一下吧！https://afdian.net/pmx1119')
                        continue
                    elif input_text == '不好用' or input_text == '否':
                        messagebox.showinfo('作者', '感谢你的支持！我会继续努力的！')
                        pause()
                        continue
                    else:
                        messagebox.showinfo('作者', '虽然你没有说什么，但是作者还是感谢你的支持！')
                        messagebox.showinfo('作者', '最后给你个惊喜吧~')
                        while fedfdk != 100:
                            fedfdk = random.randint(1, 101)
                            print('潤瑣灹⁥瑨汭㰾瑨汭㰾敨摡㰾敭慴挠慨獲瑥∽瑵ⵦ㘱㸢琼瑩敬唾瑮瑩敬⁤潄畣敭瑮⼼楴汴㹥⼼敨摡㰾潢祤猠祴敬∽慰摤湩㩧〱硰㸢迩ꪬ臣辍蛥醅铩뺱蓮蒗藥覱軩ꊛꗥ鎶뷨龬諩鲂듧ꞩ臮醔铩붱맧몒裮ꎮ鷦蚻맧蚊若랋雩ꆈ铮몑뻨蒁铩붱臣肮釥龚郩겂蓮鮔뇥醅迩뎊뷦趏裦鶴釩ꂮ듥뒤믦ꢷ铩莲菦뮑뻨肿믧ꒇ듧鎨雦覱郩결듧钶곥겂若늘跩袶铮鮔뇥趃믧낳迥讏')
                            print('閺嬫鏁栧瀛樼爱閿涘奔绌跺妞剧鐏炴唻绱濈仦杈ㄦ箒鐏忓繐褰涢敍灞艰雹娴ｆ稖瀚㈤張澶婂帨閵嗗倷绌堕懜宥堝煘閿涘奔绮犻崣锝呭弳閵嗗倸鍨甸弸浣哄閿涘本澧犻柅姘眽閵嗗倸顦茬悰灞炬殶閸椾焦顒為敍宀冪湲閻掕泛绱戦張妞尖偓鍌氭埂閸︽澘閽╅弮鍑ょ礉鐏炲鍨楁穱銊у姧閿涘本婀侀懝顖滄暞缂囧孩鐫滃鎴狀伓娑斿鐫橀妴鍌炴Ж闂勫奔姘﹂柅姘剧礉妤︼紕濮惄鎼佹閵嗗倸鍙炬稉顓炵窔閺夈儳顫掓担婊愮礉閻㈠嘲銈崇悰锝囨絻閿涘本鍊濇俊鍌氼樆娴滄亽鈧倿绮嶉崣鎴濈€顐礉楠炶埖鈧紕鍔ч懛顏冪閵嗭拷')
                            messagebox.showinfo(' ', '閺嬫鏁栧瀛樼爱閿涘奔绌跺妞剧鐏炴唻绱濈仦杈ㄦ箒鐏忓繐褰涢敍灞艰雹娴ｆ稖瀚㈤張澶婂帨閵嗗倷绌堕懜宥堝煘閿涘奔绮犻崣锝呭弳閵嗗倸鍨甸弸浣哄閿涘本澧犻柅姘眽閵嗗倸顦茬悰灞炬殶閸椾焦顒為敍宀冪湲閻掕泛绱戦張妞尖偓鍌氭埂閸︽澘閽╅弮鍑ょ礉鐏炲鍨楁穱銊у姧閿涘本婀侀懝顖滄暞缂囧孩鐫滃鎴狀伓娑斿鐫橀妴鍌炴Ж闂勫奔姘﹂柅姘剧礉妤︼紕濮惄鎼佹閵嗗倸鍙炬稉顓炵窔閺夈儳顫掓担婊愮礉閻㈠嘲銈崇悰锝囨絻閿涘本鍊濇俊鍌氼樆娴滄亽鈧倿绮嶉崣鎴濈€顐礉楠炶埖鈧紕鍔ч懛顏冪閵嗭拷')
while True:
    if not file_exists('not_beta'):
        if not file_exists('user.wqt'):
            print('\033[1;34m beta\033[0m')
            # Warning_1('为什么会出现这个？（在用户名框输入1，密码框输入2，密钥框输入3获取帮助）')
            print('输入beta用户名(若您加入了beta测试，请向作者咨询.没有请输入1)')
            print('格式应为name_XXXXXXXXXX')
            beta_name_1 = input('beta用户名:')
            print('输入beta密码(若您加入了beta测试，请向作者咨询)')
            print('格式应为password_XXXXXXXXXX')
            beta_password_1 = input('beta密码:')    
            print('输入beta密钥(若您加入了beta测试，请向作者咨询)')
            print('格式应为key_XXXXX-XXXXX-XXXXX-XXXXX-XXXXX')
            beta_key = input('beta密钥:')
            if beta_name_1 in beta_user:
                zifu(5)
                print('用户存在。')
                if beta_password_1 in beta_user[beta_name_1]:
                    zifu(5)
                    if beta_key in beta_user[beta_name_1] :
                        zifu(5)
                        print('密钥正确。')
                        print('验证成功')
                        time.sleep(3)                
                        start_wqt()
                    else:
                        cls()
                        print('\033[1;34m beta\033[0m')
                        print('\033[4;31m密钥错误！\033[0m')
                        pause()
                        cls()
                else:
                    cls()
                    print('\033[1;34m beta\033[0m')
                    print('\033[4;31m密码错误！\033[0m')
                    pause()
                    cls()
            else:
                cls()
                print('\033[1;34m beta\033[0m')
                print('\033[4;31m用户名错误！\033[0m')
                pause()
                cls()
        else:
            print('\033[1;34m beta\033[0m')
            print('发现目录下存在user.wqt文件，正在验证...')
            time.sleep(3)
            print('*************日志区*************')
            print('Open user.wqt in read-only mode')
            beta_name_1 = read_value('n')
            print('Obtain username')
            beta_password_1 = read_value('p')
            print('Obtain password')
            beta_key = read_value('k')
            print('Obtain key')
            print('***********beta用户凭证***********')
            print(f'用户名称:{beta_name_1}         ')
            print(f'用户密码:{beta_password_1}     ')
            print(f'用户密钥:{beta_key}            ')
            print(f'邮箱:None                      ')
            print(f'QQ:None                        ')
            print(f'Auto login status: OPEN        ')
            print(f'Account Status: Normal          ')
            print(f'Are a beta user: True           ')
            print('***********beta用户凭证***********')
            print('请确认')
            pause()
            if beta_name_1 in beta_user:
                zifu(5)
                print('用户存在。')
                if beta_password_1 in beta_user[beta_name_1]:
                    zifu(5)
                    if beta_key in beta_user[beta_name_1] :
                        zifu(5)
                        print('密钥正确。')
                        print('验证成功')
                        time.sleep(3)                
                        start_wqt()
                    else:
                        cls()
                        print('\033[1;34m beta\033[0m')
                        print('\033[4;31m密钥错误！请修改自动登录文件！\033[0m')
                        pause()
                        cls()
                else:
                    cls()
                    print('\033[1;34m beta\033[0m')
                    print('\033[4;31m密码错误！请修改自动登录文件！\033[0m')
                    pause()
                    cls()
            else:
                cls()
                print('\033[1;34m beta\033[0m')
                print('\033[4;31m用户名错误！请修改自动登录文件！\033[0m')
                pause()
                cls()
    else:
        pass